螺旋矩阵
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
java
class Solution {
public int[][] generateMatrix(int n) {
int[][] array = new int[n][n];
int x = 0,y = 0;
array[x][y] = 1;
int sum = 1;
while (sum < n*n) {
while (y+1 < n && array[x][y+1] == 0) {array[x][++y] = ++sum;}
while (x+1 < n && array[x+1][y] == 0) {array[++x][y] = ++sum;}
while (x-1 >= 0 && array[x-1][y] == 0) {array[--x][y] = ++sum;}
while (y-1 >= 0 && array[x][y-1] == 0) {array[x][--y] = ++sum;}
}
return array;
}
}