螺旋矩阵 II
1. 题目描述
提示
题目链接:https://leetcode.cn/problems/spiral-matrix-ii/description/
2. 解题思路
核心总结
- 核心原则:循环不变量(处理边时坚持“左闭右开”)。
- 五个关键变量:
loop:控制圈数。
startx, starty:起始坐标。
offset:边界缩进。
count:当前填入数字。
mid:正中心(奇数情况)。
- 填充动作:上 -> 右 -> 下 -> 左,顺序严格一致。
💡 易错点
- Java 中
while(loop) 不合法,必须写 while(loop > 0)。
- 每一圈内部的指针
i 和 j 必须重新对齐到 startx/starty。
n 为奇数时需单独处理最中心的点。
3. 代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| class Solution {
public int[][] generateMatrix(int n) {
int startx = 0,starty = 0;
int count = 1;
int j,i;
int offset = 1;
int loop = n/2;
int[][] matr = new int[n][n];
while(loop > 0){
for(j = starty;j < n - offset;j++){
matr[startx][j] = count;
count++;
}
for(i = startx;i < n - offset;i++){
matr[i][j] = count;
count++;
}
for(;j > starty;j--){
matr[i][j] = count;
count++;
}
for(;i > startx;i--){
matr[i][j] = count;
count++;
}
startx++;
starty++;
offset++;
loop--;
}
if(n%2==1){
matr[n/2][n/2] = count;
}
return matr;
}
}
|
4. 复杂度分析
- 时间复杂度:$O(n)$
- 空间复杂度:$O(1)$
5. 总结与反思