• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Finger Offer 29. Print matrix clockwise

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

Example 1: input: matrix = [[1, 2, 3], [4 and 6], [7,8,9]] output:,2,3,6,9,8,7,4,5 [1] example 2: input: Matrix = [[1, 2, 3, 4], [5,6,7,8], [9,10,11,12]] output:,2,3,4,8,12,11,10,9,5,6,7 [1]Copy the code

Train of thought

  • Let’s start with a two-dimensional array
    • The only thing that’s changing when you’re traversing the snake is up, down, left, right
    • So we need to maintain four variablesThe up and down or so
    • Four variables to control where we areA two-dimensional matrixWalk to the end each time
    • You need to carry out each maintenance boundary variableMinus oneorGal.The operation of the
    • It is important to note that the variables corresponding to each loop should correspond one to one
    • This problem can also be done with four cursors, so as not to cross boundaries
class Solution {
    public int[] spiralOrder(int[][] matrix) {
        
        if(matrix == null ||matrix.length == 0) {return new int[0];
        }
        
        // Initialize up, down, left, and right
        int left = 0, top = 0;
        int right = matrix[0].length-1;
        int bottom = matrix.length - 1;
        int[] res = new int[(right+1)*(bottom+1)];
        int k = 0;
        
        // Loop print
        while(top <= bottom && left <= right){
            for (int i = left; i <= right; i++) { / / left to right
                res[k++] = matrix[top][i];
            }
            top ++;   // assume that the first time, top++ means that the first line has been completed
            for (int i = top; i <= bottom; i++) { / / top to bottom
                res[k++] = matrix[i][right];
            }
            right --;
            for (int i = right; i >= left && top <= bottom; i--) {    / / right to left
                res[k++] = matrix[bottom][i];
            }
            bottom --;
            for (int i = bottom; i >= top && left <= right; i--) {    / / the bottom up
                res[k++] = matrix[i][left];
            }
            left ++;
        }
        returnres; }}Copy the code