LeetCode 剑指offerQ29顺时针打印矩阵 java100%

思路

通过top、bottom、left、right四个变量来控制矩阵的边界,每次打印完便更新矩阵的边界,边界外的都是已经打印好的。这样,每次打印便可以分解为四个动作:

  1. print(m[top][left->right]), top++
  2. print(m[top->bottom][right]),right–
  3. print(m[bottom][right->left]),bottom–
  4. print(m[bottom->top][left]),left++
    注意,每个动作结束后都要对边界进行更新。

代码

class Solution {
    public int[] spiralOrder(int[][] matrix) {
       int rows=matrix.length;
       if(rows==0) return new int[0];
       int cols=matrix[0].length;
       if(cols==0) return new int[0];
       int re[]=new int[cols*rows];
       sub(re,0,0,0,rows-1,0,cols-1,matrix);
       return re;
    } 
    void sub(int[] re,int index,int indicator,int top,int bottom,int left,int right,int[][] m){
        if(top>bottom||left>right) return;
        
        if(indicator==0){
            for(int i=index;i<=index+right-left;i++){
                re[i]=m[top][left+i-index];
            }
            sub(re,index+right-left+1,1,top+1,bottom,left,right,m);
        }else if(indicator==1){
            for(int i=index;i<=index+bottom-top;i++){
                re[i]=m[top+i-index][right];
            }
            sub(re,index+bottom-top+1,2,top,bottom,left,right-1,m);
        }else if(indicator==2){
            for(int i=index;i<=index+right-left;i++){
                re[i]=m[bottom][right+index-i];
            }
            sub(re,index+right-left+1,3,top,bottom-1,left,right,m);
        }else{
            for(int i=index;i<=index+bottom-top;i++){
                re[i]=m[bottom+index-i][left];
            }
            sub(re,index+bottom-top+1,0,top,bottom,left+1,right,m);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值