TypechoJoeTheme

Toasobi的博客

顺时针打印矩阵(简单)

本文最后更新于2023年03月16日,已超过553天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!

这道题主要可以使用模拟法来做。可以模拟打印矩阵的路径。初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,顺时针旋转,进入下一个方向。

判断路径是否进入之前访问过的位置需要使用一个与输入矩阵大小相同的辅助矩阵 \textit{visited}visited,其中的每个元素表示该位置是否被访问过。当一个元素被访问时,将 \textit{visited}visited 中的对应位置的元素设为已访问。

如何判断路径是否结束?由于矩阵中的每个元素都被访问一次,因此路径的长度即为矩阵中的元素数量,当路径的长度达到矩阵中的元素数量时即为完整路径,将该路径返回。

仔细想一想,这道题好像和DP有点像。。

下面是代码(注释讲解):

<div>class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }
        int rows = matrix.length, columns = matrix[0].length; //目标矩阵的行和列
        boolean[][] visited = new boolean[rows][columns]; //构建一个访问矩阵
        int total = rows * columns; //记录一下总数据个数(用行*列)
        int[] order = new int[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[i] = 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;
    }
}</div>
朗读
赞(1)
评论 (0)