class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int flag = 1;
int p =0,q=0;
for (int i = 0; i < n*n; i++) {
res[p][q] = i+1;
if (flag == 1) {
q++;
if (q>=n || res[p][q]!=0) {
flag++;
q--;
p++;
}
} else if (flag == 2) {
p++;
if (p>=n || res[p][q]!=0) {
flag++;
p--;
q--;
}
} else if (flag == 3) {
q--;
if (q<0 || res[p][q]!=0) {
flag++;
q++;
p--;
}
} else if (flag == 4) {
p--;
if (p<0 || res[p][q]!=0) {
flag=1;
p++;
q++;
}
}
}
return res;
}
}
leetcode 59. 螺旋矩阵 II
最新推荐文章于 2025-01-03 20:58:06 发布