LeetCode 59. Spiral Matrix II
Woodyiiiiiii opened this issue · comments
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
跟I题一样的思路。又因为这是正方形矩阵,中间的剩余部分的边界判断可以省略。
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
if (n == 0) {
return matrix;
}
int left = 0, right = n - 1, top = 0, bottom = n - 1;
int i = 0, j = 0;
int val = 1;
while (left <= right && top <= bottom) {
for (j = left; j <= right; ++j) {
matrix[top][j] = val++;
}
if (top == bottom) {
break;
}
for (i = top + 1; i <= bottom; ++i) {
matrix[i][right] = val++;
}
if (left == right) {
break;
}
for (j = right - 1; j >= left; --j) {
matrix[bottom][j] = val++;
}
for (i = bottom - 1; i > top; --i) {
matrix[i][left] = val++;
}
++left;
++top;
--right;
--bottom;
}
return matrix;
}
}
参考资料:
LeetCode原题