🌕 59. 螺旋矩阵 II
2022年6月9日
- algorithm
🌕 59. 螺旋矩阵 II
难度: 🌕
问题描述
解法
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 cur = 1;
while(left <= right && top <= bottom) {
if(left <= right && top <= bottom) {
// left -> right
for(int j = left; j <= right; j ++) {
res[top][j] = cur;
cur ++;
}
}
top ++;
if(left <= right && top <= bottom) {
// top -> bottom
for(int i = top; i <= bottom; i ++) {
res[i][right] = cur;
cur ++;
}
}
right --;
if(left <= right && top <= bottom) {
// right -> left
for(int j = right; j >= left; j --) {
res[bottom][j] = cur;
cur ++;
}
}
bottom --;
if(left <= right && top <= bottom) {
// bottom -> top
for(int i = bottom; i >= top; i --) {
res[i][left] = cur;
cur ++;
}
}
left ++;
}
return res;
}
}