54.螺旋矩阵


54.螺旋矩阵

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

示例 1:

img

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

示例 2:

img

输入: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

题解:

import java.util.ArrayList;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return arrayList;
        }
        int rows = matrix.length;
        int columns = matrix[0].length;
        boolean[][] boolMatrix = new boolean[rows][columns];
        int total = rows * columns;
        int row = 0;
        int column = 0;
        // 初始往右走
        int[][] direc = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int index = 0;
        for (int i = 0; i < total; i++) {
            arrayList.add(matrix[row][column]);
            boolMatrix[row][column] = true;
            int nextRow = row + direc[index][0];
            int nextCol = column + direc[index][1];
            // boolMatrix中为true则证明走过
            // 要走的下一列长度大于总列数或小于0则换方向
            // 要走的下一行长度大于总行数或小于0则换方向
            if (nextCol < 0 || nextRow >= rows || nextRow < 0 || nextCol >= columns || boolMatrix[nextRow][nextCol]) {
                index = (index + 1) % 4;
            }
            row += direc[index][0];
            column += direc[index][1];
        }
        return arrayList;
    }
}

文章作者: Feliks
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Feliks !
评论
  目录