54. 螺旋矩阵

176 阅读1分钟

思路

  • 用行指针h,列指针v来控制遍历范围,遍历上下左右四个边。
  • count记录遍历过的元素个数,控制count小于元素总个数m*n
  • 注意可能存在的重复遍历:当只剩下一行时。

IMG_11DCFBAD5720-1.jpeg

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int length = matrix[0].length, width = matrix.length;
        int total = width * length; //元素总个数
        int count = 0; //遍历过的元素个数
        int top = 0, bottom = width - 1, left = 0, right = length - 1;
        while (count < total) {
            // 左->右
            for (int i = left; i <= right; i++) {
                res.add(matrix[top][i]);
                count++;
            }
            // 上->下
            for (int i = top + 1; i < bottom; i++) {
                res.add(matrix[i][right]);
                count++;
            }
            // 右->左 避免只剩一行时重复
            for (int i = right; i >= left && top != bottom; i--) {
                res.add(matrix[bottom][i]);
                count++;
            }
            // 下->上 避免只剩一列时重复
            for (int i = bottom - 1; i > top && left != right; i--) {
                res.add(matrix[i][left]);
                count++;
            }
            // 收缩
            top++;
            bottom--;
            left++;
            right--;
        }
        return res;
    }
}
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int u = 0, v = matrix[0].length - 1, m = 0, n = matrix.length - 1;
        int size = matrix[0].length * matrix.length;
        List<Integer> res = new ArrayList<>();
        int count = 0;
        while (count < size) {
            for (int i = u; i <= v; i++) {
                res.add(matrix[m][i]);
                count++;
            }
            for (int i = m + 1; i < n; i++) {
                res.add(matrix[i][v]);
                count++;
            }
            if (count < size) {
                for (int i = v; i >= u; i--) {
                    res.add(matrix[n][i]);
                    count++;
                }
            }
            if (count < size) {
                for (int i = n - 1; i > m; i--) {
                    res.add(matrix[i][u]);
                    count++;
                }
            }
            
            u++;
            v--;
            m++;
            n--;
        }
        return res;
    }
}