LeetCode Interview Question 29. Print the matrix clockwise

topic

Enter a matrix and print out each number in clockwise order from the outside to the inside. link

Ideas

Simulation is not easy to think of the loop method. Can only look at the solution. .

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, x = 0;
        int[] res = new int[(right + 1) * (bottom + 1)];
        while(true) {
    
    
            for(int i = left; i <= right; i++){
    
    
                res[x++] = matrix[top][i]; // left to right.
            }
            //top下移,top之上的行全部遍历过 
            if(++top > bottom) break;
            for(int i = top; i <= bottom; i++){
    
     
                res[x++] = matrix[i][right]; // top to bottom.
            }
            //right左移,right右边的列全部遍历过
            if(left > --right) break;
            for(int i = right; i >= left; i--){
    
     
                res[x++] = matrix[bottom][i]; // right to left.
            }
            //bottom上移,bottom之下的行全部遍历过
            if(top > --bottom) break;
            for(int i = bottom; i >= top; i--){
    
     
                res[x++] = matrix[i][left]; // bottom to top.
            }
            //left右移,left左边的列全部遍历过
            if(++left > right) break;
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_42007742/article/details/106578169