LeetCode—Sword refers to Offer: Print matrix clockwise (violent)

Print matrix clockwise (simple)

August 25, 2020

Question source: Likou

Insert picture description here

Solving the problem According to the
problem, the order is to go right, go down, go left, and go up. Use this as a regular cycle.

Need to set four boundaries, shrink the boundary every time you finish

class Solution {
    
    
    public int[] spiralOrder(int[][] matrix) {
    
    
        if(matrix.length==0) return new int[0];
        //求四边界
        int left=0,right=matrix[0].length-1,top=0,bottom=matrix.length-1,id=0;
        int[] res=new int[(right+1)*(bottom+1)];
        while(true){
    
    
            //走上边界
            for(int i=left;i<=right;i++){
    
    
                res[id++]=matrix[top][i];
            }
            //上边界走完了,收缩
            if(++top>bottom) break;
            //走右边界
            for(int i=top;i<=bottom;i++){
    
    
                res[id++]=matrix[i][right];
            }
            //右边界走完了,收缩
            if(--right<left) break;
            //走下边界
            for(int i=right;i>=left;i--){
    
    
                res[id++]=matrix[bottom][i];
            }
            //下边界走完了,收缩
            if(--bottom<top) break;
            //走左边界
            for(int i=bottom;i>=top;i--){
    
    
                res[id++]=matrix[i][left];
            }
            //左边界走完了,收缩
            if(++left>right) break;
        }
        return res;
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_41541562/article/details/108212777