难度:中等
给你一个正整数
n
,生成一个包含1
到n2
所有元素,且元素按顺时针顺序螺旋排列的n x n
正方形矩阵matrix
。示例 1:
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]示例 2:
输入:n = 1 输出:[[1]]提示:
1 <= n <= 20
代码:
class Solution {
public int[][] generateMatrix(int n) {
int top = 0, left = 0, bottom = n - 1, right = n - 1;
int count = 1;
int[][] result = new int[n][n];
while (count <= n * n) {
//从左到右
for (int i = left; i <= right && count >= 1; i++) {
result[top][i] = count;
count++;
}
top++;
//从上到下
for (int i = top; i <= bottom && count >= 1; i++) {
result[i][right] = count;
count++;
}
right--;
//从右到左
for (int i = right; i >= left && count >= 1; i--) {
result[bottom][i] = count;
count++;
}
bottom--;
//从右到左
for (int i = bottom; i >= top && count >= 1; i--) {
result[i][left] = count;
count++;
}
left++;
}
return result;
}
}