59. 螺旋矩阵Ⅱ
思路:
模拟顺时针画矩阵的过程:
- 填充上行从左到右
- 填充右列从上到下
- 填充下行从右到左
- 填充左列从下到上
画每四条边,每画一条边都要坚持一致的左闭右开
因为此题一定是正方形,所以不用考虑长方形的情况
但是本题需要考虑n为奇或偶的情况,奇的话就会有一个循环不到,偶的话能循环完毕
代码实现
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
int count = 0;
while (count != n * n) {
for (int i = 0; i < right - left; i++) {
res[top][left + i] = ++count;
}
for (int i = 0; i < bottom - top; i++) {
res[top + i][right] = ++count;
}
for (int i = 0; i < right - left; i++) {
res[bottom][right - i] = ++count;
}
for (int i = 0; i < bottom - top; i++) {
res[bottom - i][left] = ++count;
}
if (left == right) {
res[left][left] = ++count;
}
left++;
right--;
top++;
bottom--;
}
return res;
}
}