LeetCode54.旋转矩阵 -- 模拟旋转路径

2 篇文章 0 订阅
2 篇文章 0 订阅

本题解析,主要是根据LeetCode官方给出的答案,进行每一步代码的详细介绍。原题链接https://leetcode-cn.com/problems/spiral-matrix/solution/luo-xuan-ju-zhen-by-leetcode-solution/

1.问题描述

 

2.思路

模拟螺旋矩阵的路径,假设初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,顺时针旋转,进入下一个方向,其中方向的转变是由给定的方向矩阵directions实现的。

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

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

3.详细代码

public class Solution54 {
    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new LinkedList<>();
        if (matrix==null|| matrix.length==0||matrix[0].length==0){
            return result;
        }
        //获取二维数组的行和列
        int rows = matrix.length;
        int columns = matrix[0].length;
        //总共元素个数
        int total = rows*columns;
        //定义一个相同大小的辅助矩阵visited
        boolean[][] visited = new boolean[rows][columns];
        //定义一个方向矩阵directions
        int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
        //定义遍历方向directionIndex
        int directionIndex = 0;
        //定义遍历启始位置
        int row = 0;
        int column = 0;
        for (int i = 0;i<total;i++){
            result.add(matrix[row][column]);
            visited[row][column] = true;
            //定义下一个遍历位置
            int nextRow = row + directions[directionIndex][0],nextColumn = column + directions[directionIndex][1];
            //根据边界条件,得出下一次遍历方向
            if (nextRow>=rows||nextRow<0||nextColumn>=columns||nextColumn<0||visited[nextRow][nextColumn]){
                directionIndex = (directionIndex + 1)%4;
            }
            row+=directions[directionIndex][0];
            column+=directions[directionIndex][1];
        }
        return result;
    }
}

 4.运行结果

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值