- 时间:2020-07-03
- 题目链接:https://leetcode-cn.com/problems/spiral-matrix-ii
- tag:
矩阵
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
参考螺旋矩阵
一模一样的
class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
if (n < 1) {
return result;
}
int top = 0, left = 0, bottom = n - 1, right = n - 1, x = 1;
while(top <= bottom && left <= right) {
for (int col = left; col <= right; col++) {
result[top][col] = x;
x++;
}
for(int row = top + 1; row <= bottom; row++) {
result[row][right] = x;
x++;
}
if (top < bottom && left < right) {
for(int col = right - 1; col >= left; col--) {
result[bottom][col] = x;
x++;
}
for(int row = bottom - 1; row >= top + 1; row--) {
result[row][left] = x;
x++;
}
}
top++;
left++;
bottom--;
right--;
}
return result;
}
}