Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

题意:

给定n, 把1至n ^ 2所有的数,按照螺旋顺序填入方阵。

code

 /*
Time: O(n^2)
Space: O(n^2)
*/
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
if (n == 0) return matrix;
int beginX = 0, endX = n - 1;
int beginY = 0, endY = n - 1;
int num = 1;
while (true) {
for (int j = beginX; j <= endX; ++j) matrix[beginY][j] = num++;
if (++beginY > endY) break; for (int i = beginY; i <= endY; ++i) matrix[i][endX] = num++;
if (beginX > --endX) break; for (int j = endX; j >= beginX; --j) matrix[endY][j] = num++;
if (beginY > --endY) break; for (int i = endY; i >= beginY; --i) matrix[i][beginX] = num++;
if (++beginX > endX) break;
}
return matrix;
}
}
05-07 15:46