文章

54.螺旋矩阵

54.螺旋矩阵

题目

原题 54.螺旋矩阵

解题

进行螺旋遍历🌀的本质实际上是找到每个需要遍历的边

  1. 遍历最上侧的边 top, 遍历完毕后将 top++。
  2. 遍历最右侧的边 right, 遍历完毕后将 right–。
  3. 遍历最底部的边 bottom, 遍历完毕后将 bottom–。
  4. 遍历最左侧的边 left, 遍历完毕后将 left++。

注意:

  • 每次在遍历的时候都将相应的边界进行了收窄,这样也就能够避免遍历完 top 边界和 right 边界的时候出现重复元素的情况。
  • 需要注意处理 bottom 和 left 时不能够重复记录。

具体的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public List<Integer> spiralOrder(int[][] matrix) {
    int m = matrix.length;
    int n = matrix[0].length;
    int top = 0; int bottom = m - 1;
    int left = 0; int right = n - 1;
    ArrayList<Integer> res = new ArrayList<>();
    while (top<=bottom && left<=right){
        // 处理最上面一行
        for (int i = left; i<=right; i++){
            res.addLast(matrix[top][i]);
        }
        top++;
        // 处理最右侧的列
        for (int i = top; i<=bottom; i++){
            res.addLast(matrix[i][right]);
        }
        right--;
        // 处理最底部的行,避免重复处理
        for (int i = right; i>=left&&(top-1)!=bottom; i--){
            res.addLast(matrix[bottom][i]);
        }
        bottom--;
        // 处理最左侧的列,避免重复处理
        for (int i=bottom; i>=top&&left!=(right+1); i--){
            res.addLast(matrix[i][left]);
        }
        left++;
    }
    return res;
}
本文由作者按照 CC BY 4.0 进行授权