解题思路
54. 螺旋矩阵
对于每个二维数组,都按照图中所示的红绿蓝紫依次遍历,然后不断收缩,继续以相同方式遍历里面的小二维数组。
因为二维数组就是个矩阵,收缩矩阵就要定义上下左右四个边界。
代码
class Solution {
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>(); //存储结果
//定义顶行:row1 , 底行:row2 ; 左列col1 , 右列:col2
int row1 = 0,row2 = matrix.length-1;
int col1 = 0,col2 = matrix[0].length-1;
while(row1<=row2 && col1<=col2) {
for(int col = col1 ; col <= col2 ; col++) { //将上面的行向右加入
result.add(matrix[row1][col]);
}
for(int row = row1+1 ; row<=row2 ; row++) { //将右边的列向下加入
result.add(matrix[row][col2]);
}
if(row1<row2 && col1 < col2) {
for(int col = col2-1 ; col>col1 ;col--) { //将下面的行向左加入
result.add(matrix[row2][col]);
}
for(int row = row2 ; row>row1 ; row--) { //将左边的列向上加入
result.add(matrix[row][col1]);
}
}
row1++;
row2--;
col1++;
col2--;
}
return result;
}
}