Given positive integer n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.
Input: 3 → Output: [[1,2,3],[8,9,4],[7,6,5]]Input: 1 → Output: [[1]]
Same boundary shrinking approach but write numbers 1 to n^2 in spiral order.
- Same four-boundary approach as Spiral Matrix.
- Write num from 1 to n^2 while filling.
class Solution {
public int[][] generateMatrix(int n) {
int[][] mat = new int[n][n];
int top=0, bottom=n-1, left=0, right=n-1, num=1;
while (top<=bottom && left<=right) {
for (int c=left;c<=right;c++) mat[top][c]=num++; top++;
for (int r=top;r<=bottom;r++) mat[r][right]=num++; right--;
if (top<=bottom) { for (int c=right;c>=left;c--) mat[bottom][c]=num++; bottom--; }
if (left<=right) { for (int r=bottom;r>=top;r--) mat[r][left]=num++; left++; }
}
return mat;
}
}
- Time Complexity: O(N^2)
- Space Complexity: O(1) extra