leetcode 54 螺旋矩阵

LeetCode 54 螺旋矩阵

在给定矩阵中,以螺旋的顺序(右->下->左->上->右)遍历所有元素并输出
方法: 方向数组

  • 方向数组中存储一组与方向向量,每个方向上遍历过程需要用到该方向的方向向量来完成坐标的转换
  • 方向数组中的所有方向向量以循环的方式被使用,切换的条件是该方向的遍历到达边界:row-1<0; row+1=rows; col-1<0; col+1=cols; 下一元素已访问
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<Integer>();      //输出
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return order;
        }
        int rows = matrix.length, columns = matrix[0].length;
        boolean[][] visited = new boolean[rows][columns];
        int total = rows * columns;      //遍历元素个数达到total,结束遍历
        int row = 0, column = 0;
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};      //方向矩阵: 右、下、左、上
        int directionIndex = 0;
        for (int i = 0; i < total; i++) {
            order.add(matrix[row][column]);
            visited[row][column] = true;
            //该方向是否遍历结束,方向切换(循环方式)
            int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
            if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
                directionIndex = (directionIndex + 1) % 4;
            }
            //坐标切换(求下一遍历坐标)
            row += directions[directionIndex][0];
            column += directions[directionIndex][1];
        }
        return order;
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13298774.html