顺时针打印矩阵(带注释)

本文详细介绍了如何实现一个矩阵螺旋遍历的算法,从右上角开始,按照顺时针方向遍历整个矩阵。关键点包括建立访问标记、确定行走方向和判断是否需要改变方向。时间复杂度和空间复杂度均为O(m*n),其中m和n分别为矩阵的行数和列数。
摘要由CSDN通过智能技术生成
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;
        int colums = matrix[0].length;
        boolean [][] visited = new boolean[rows][colums];
        int[][] direction={{0,1},{1,0},{0,-1},{-1,0}};//顺时针移动时,右,下,左,上时对应的行列变化。
        int directionIndex = 0;//用于定义右下左上的选择--direction[direcionindex],,if判断后的取余操作,实现了directionIndex的循环。
        int totals = rows*colums;//矩阵中所有的元素
        int[] order = new int[totals];//输出要求的数组
        int row = 0,colum = 0;
        for(int i = 0;i < totals;i++){
            order[i] = matrix[row][colum];
            visited[row][colum] = true;//每访问一个元素,定好标记。
            //下次要访问的坐标行列
            int nextRow = row + direction[directionIndex][0];
            int nextColum = colum + direction[directionIndex][1];
            //判断方向转变
            if(nextRow < 0||nextRow >= rows||nextColum < 0||nextColum >= colums||visited[nextRow][nextColum]){
                directionIndex = (directionIndex+1)%4;
            }
            row += direction[directionIndex][0];
            colum += direction[directionIndex][1];             
        }
        return order;
    }
}

问在leetcode中把boolean小写

顺时针走右下左上开始循环。

关键点:

建立访问标记

确定行走方向

确定行走方向的行列变化。

对下一次访问位置判定是否需要改变方向

时间复杂度:

访问矩阵中的每一个元素,所以O(m*n)。

空间复杂度:

建立了与矩阵同大小的visited矩阵所以为O(m*n)。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值