解题思路
59. 螺旋矩阵 II
该题54. 螺旋矩阵的思路是一样的。
每层都按红绿蓝紫的顺序把1~n^2依次添加进行
代码
class Solution {
public static int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int value = 1;
int row1 = 0, row2 = n-1;
int col1 = 0, col2 = n-1;
while(row1<=row2 && col1<=col2) {
for(int col = col1 ; col <= col2 ; col++) { //将上面的行向右加入
matrix[row1][col] = value++;
}
for(int row = row1+1 ; row<=row2 ; row++) { //将右边的列向下加入
matrix[row][col2] = value++;
}
if(row1<row2 && col1 < col2) {
for(int col = col2-1 ; col>col1 ;col--) { //将下面的行向左加入
matrix[row2][col] = value++;
}
for(int row = row2 ; row>row1 ; row--) { //将左边的列向上加入
matrix[row][col1] =value++;
}
}
row1++;
row2--;
col1++;
col2--;
}
return matrix;
}
}