54. 螺旋矩阵

Difficulty: 中等

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:

54.螺旋矩阵 - 图1

  1. 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
  2. 输出:[1,2,3,6,9,8,7,4,5]

示例 2:

54.螺旋矩阵 - 图2

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

Solution

四个指针来进行定位遍历,top,right,bottom,right

  • left—right,top++
  • top—bottom right++
  • right—left bottom—
  • bottom—top left++

    特别要注意的是,在一次循环里,如果矩阵是奇数行、偶数列的时候有问题,会出错,这时要在循环体内多判断退出条件

class Solution {
     public List<Integer> spiralOrder(int[][] matrix) {
        if (matrix == null) {
            return null;
        }
        if (matrix.length == 0) {
            return new ArrayList<>();
        }
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;

        List<Integer> list = new ArrayList<>();

        while (left <= right && top <= bottom) {
            for (int i = left; i <= right; i++) {
                list.add(matrix[top][i]);
            }
            top++;
            for (int i = top; i <= bottom; i++) {
                list.add(matrix[i][right]);
            }
            right--;
            if (left > right || top > bottom) {
                break;
            }
            for (int i = right; i >= left; i--) {
                list.add(matrix[bottom][i]);
            }
            bottom--;

            for (int i = bottom; i >= top; i--) {
                list.add(matrix[i][left]);
            }
            left++;
        }
        return list;
    }
}