class Solution {
public int[][] generateMatrix(int n) {
if(n<=0) return new int[0][0];
int[][] res=new int[n][n];
int top=0;
int bottom=n-1;
int left=0;
int right=n-1;
int flag=1;
while(top<=bottom&&left<=right) {
//top left->top right
for(int i=left;i<=right;i++) {
res[top][i]=flag++;
}
top++;
//top right->bottom right
for(int i=top;i<=bottom;i++) {
res[i][right]=flag++;
}
right--;
//bottom right->bottom left
for(int i=right;i>=left;i--) {
res[bottom][i]=flag++;
}
bottom--;
//bottom left->top left
for(int i=bottom;i>=top;i--) {
res[i][left]=flag++;
}
left++;
}
return res;
}
}
leetcode_59_螺旋矩阵 II
最新推荐文章于 2024-03-18 08:30:00 发布