剑指 Offer 29. 顺时针打印矩阵

本文介绍了一种Java实现的矩阵螺旋顺序打印算法,通过定义四个边界变量(left, top, right, bottom),逐层遍历矩阵的四个方向:从左到右、上到下、右到左和下到上,确保在每个阶段更新边界以避免重复。该算法的时间复杂度为O(MN),空间复杂度为O(1)。
摘要由CSDN通过智能技术生成

1、题目内容:

2、解题代码 

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix == null || matrix.length == 0) 
              return new int[] {};
        //left, right, top, bottom四个变量
        int left = 0;
        int top = 0;
        int right = matrix[0].length-1;
        int bottom = matrix.length-1;
        int[] pOrder = new int[(right+1) * (bottom+1)];
        //k代表数组个数
        int k = 0;
        while(true){
            //从左到右(left --right)
            for(int j = left; j<= right ; j++){ 
                pOrder[k++] = matrix[top][j];
            }
            if(++top > bottom) break;
            //从上到下(top --bottom)
            for(int i = top; i <= bottom; i++){
                pOrder[k++] = matrix[i][right];
            }
            if(left > --right) break;
            //从右到左
            for(int j = right ; j >= left ; j--){
                pOrder[k++] = matrix[bottom][j];
            }
            if(top > --bottom)break;
            //从下到上
            for(int i= bottom ; i >= top; i--){
                pOrder[k++] = matrix[i][left];
            }
            if(++left > right ) break;
        }
        return pOrder;
    }

}

3、注意事项

3-1、关键点

需要找到4个点,【上】-top 【下】-bottom 【左】-left 【右】-right,并且边界概念要很清晰

3-2、复杂度

时间复杂度 O(MN):M,N 分别为矩阵行数和列数。
空间复杂度 O(1): 四个边界 left , right , top , bottom 使用常数大小的 额外 空间( pOrder 为必须使用的空间)。

3-3、4个校验终止条件

if ( ++top > bottom )  break; // 从 【左上】到【右上】输出后,top自增(必须++top,不是top--,防止无下一行数据)

if ( left > --right )  break;  // 从【右上】到【右下】输出后, right自减同理

if ( top > --bottom ) break; //从【右下】到【左下】输出后, bottom自减同理

if ( ++left > right  )  break; // 从【左下】到【左上】输出后,left自增同理

3-4、输出逻辑图

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值