|
| 1 | +/* |
| 2 | + * Algorithm Name:Spiral Matrix2 . |
| 3 | + * Programming Language: Java |
| 4 | + * Category: Array ,matrix |
| 5 | + * Difficulty Level: Medium |
| 6 | + * |
| 7 | + * Author: Priya Rani |
| 8 | + * |
| 9 | + * Algorithm Description: Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. |
| 10 | + * Input: n = 3 |
| 11 | + Output: [[1,2,3],[8,9,4],[7,6,5]] |
| 12 | + Example 2: |
| 13 | + Input: n = 1 |
| 14 | + Output: [[1]] |
| 15 | +
|
| 16 | + |
| 17 | +
|
| 18 | + * Time Complexity: O(1) Time complexity: O(n²) |
| 19 | + * Space complexity: O(1) (excluding output matrix) |
| 20 | +*/ |
| 21 | +import java.util.*; |
| 22 | + |
| 23 | +public class SpiralMatrixII { |
| 24 | + public int[][] generateMatrix(int n) { |
| 25 | + int[][] matrix = new int[n][n]; |
| 26 | + int left = 0, right = n - 1; |
| 27 | + int top = 0, bottom = n - 1; |
| 28 | + int num = 1; |
| 29 | + |
| 30 | + while (left <= right && top <= bottom) { |
| 31 | + for (int i = left; i <= right; i++) { |
| 32 | + matrix[top][i] = num++; |
| 33 | + } |
| 34 | + top++; |
| 35 | + |
| 36 | + for (int i = top; i <= bottom; i++) { |
| 37 | + matrix[i][right] = num++; |
| 38 | + } |
| 39 | + right--; |
| 40 | + |
| 41 | + if (top <= bottom) { |
| 42 | + for (int i = right; i >= left; i--) { |
| 43 | + matrix[bottom][i] = num++; |
| 44 | + } |
| 45 | + bottom--; |
| 46 | + } |
| 47 | + |
| 48 | + if (left <= right) { |
| 49 | + for (int i = bottom; i >= top; i--) { |
| 50 | + matrix[i][left] = num++; |
| 51 | + } |
| 52 | + left++; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return matrix; |
| 57 | + } |
| 58 | + |
| 59 | + public static void main(String[] args) { |
| 60 | + SpiralMatrixII sm = new SpiralMatrixII(); |
| 61 | + int n = 3; |
| 62 | + int[][] result = sm.generateMatrix(n); |
| 63 | + |
| 64 | + for (int[] row : result) { |
| 65 | + System.out.println(Arrays.toString(row)); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | + |
0 commit comments