Problem
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Solution
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
if (n == 0) return res;
int num = 1, rStart = 0, rEnd = n-1, cStart = 0, cEnd = n-1;
while (rStart <= rEnd && cStart <= cEnd) {
for (int j = cStart; j <= cEnd; j++) res[rStart][j] = num++;
rStart++;
for (int i = rStart; i <= rEnd; i++) res[i][cEnd] = num++;
cEnd--;
for (int j = cEnd; j >= cStart; j--) {
if (rStart > rEnd) break;
res[rEnd][j] = num++;
}
rEnd--;
for (int i = rEnd; i >= rStart; i--) {
if (cStart > cEnd) break;
res[i][cStart] = num++;
}
cStart++;
}
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。