Problem
Given a positive integer n
, generate an n x n
matrix
filled with elements from 1
to n2
in spiral order.
Examples
Example 1:
Input: n = 3
Output: [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Example 2:
Input: n = 4
Output: [
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]
]
Similar Problems
- Spiral Matrix 1 - Return
- Spiral Matrix 3 - Traverse from Given Starting Point
- Spiral Matrix 4 - From Linked List
Solution
Method 1 - Iterative just checking boundaries
We can reuse the solution from Spiral Matrix 1 - Return#Method 1 - Iterative just checking boundaries.
Code
Java
public class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
int num = 1;
int top = 0;
int bottom = n - 1;
int left = 0;
int right = n - 1;
while (num <= n * n) {
for (int i = left; i<= right; i++) {
ans[top][i] = num++;
}
top++;
for (int i = top; i<= bottom; i++) {
ans[i][right] = num++;
}
right--;
//prevent duplicate row
if (top <= bottom) {
for (int i = right; i >= left; i--) {
ans[bottom][i] = num++;
}
bottom--;
}
// prevent duplicate column
if (left <= right) {
for (int i = bottom; i >= top; i--) {
ans[i][left] = num++;
}
left++;
}
}
return ans;
}
}