54. 螺旋矩阵
这题是模拟题,就是模拟整个遍历过程。
(这两个题间隔一段时间做,做出了两个版本,估计下一次做,又能再给一个版本)
这个题没有什么技巧,只需要耐心的分析整个过程就能写出来,只是时间问题。
分析:可以发现一次顺时针,需要从左向右走 --> 从上向下走 --> 从右向左走 --> 从下向上走,并且:
- 从左向右走完,该行已经全部遍历完了,之后不用再遍历,需要top++;同理从右向左也一样,需要bottom–
- 从上向下走完,该列已经全部遍历完了,之后不用再遍历,需要right–;同理,从下向上走,需要left++
——所以,自然的我们需要设置4个变量来限制上下、左右边界
关于循环终止条件:其实可以设置为while(true),然后在循环里面进行判断,可以发现:如果top<bottom/left>right,那么遍历就结束了——所以每次更新这4个变量其中一个的时候,都需要进行判断。
因为知道了矩阵的长和宽,所以个数是可以计算的,所以我设置了循环的终止条件:数组的长度<矩阵数字个数
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int lenRow = matrix.length; // 行数
int leCol = matrix[0].length; // 列数
int rowTop = 0, rowBottom = lenRow - 1, colLeft = 0, colRight = leCol - 1; // 初始化行列的限制
List<Integer> res = new ArrayList<>();
int count = lenRow * leCol;
while(res.size() < count){
for(int j = colLeft; j <= colRight; j++){
res.add(matrix[rowTop][j]);
}
if(++rowTop > rowBottom) break;
for(int i = rowTop; i <= rowBottom; i++){
res.add(matrix[i][colRight]);
}
if(--colRight < colLeft) break;
for(int j = colRight; j >= colLeft; j--){
res.add(matrix[rowBottom][j]);
}
if(--rowBottom < rowTop) break;
for(int i = rowBottom; i >= rowTop; i--){
res.add(matrix[i][colLeft]);
}
if(++colLeft > colRight) break;
}
return res;
}
}
——最主要:要能发现4个边界的变量,在纸上模拟一遍,就能解出。
参考:
- https://leetcode-cn.com/problems/spiral-matrix/solution/cxiang-xi-ti-jie-by-youlookdeliciousc-3/(收获是,变量名字要好好取,不然写起来太麻烦了,题解里面就是用u、d、l、r来表示上边行、下边行、左边列、右边列,下次复习记得要用这个命名方法)