The sword refers to Offer 29 (array 5). Print the matrix clockwise

The sword refers to Offer 29 (array 5). Print the matrix clockwise

Problem Description:

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

example

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

Problem-solving ideas:Idea link

Consider setting the four boundaries of the matrix "left, top, right, and bottom" to simulate the above matrix traversal order.

image-20210909145150781

The matrix has four boundaries: top, bottom, left, and right. Every time the boundary is traversed, the direction is changed, and the boundary is tightened.

There are four traversal directions in total:

  1. Left -> Right, res.append(matrix[top][i]), after traversing to the boundary, top moves down;
  2. Up -> Down, res.append(matrix[i][right]), after traversing to the boundary, right moves to the left;
  3. Right -> Left, res.append(matrix[bottom][i]), after traversing to the boundary, the bottom moves up;
  4. Down -> Up, res.append(matrix[i][left]), after traversing to the boundary, left moves to the right;

Implemented using recursive code:

class Solution {
    
    
    public int[] spiralOrder(int[][] matrix) {
    
    
        //判断矩阵是否为空
        if(matrix.length == 0 || matrix == null){
    
    
            return new int[0];
        }
        //根据顺时针的运动方式建立初始指针
        int n = matrix.length,m = matrix[0].length;
        int left = 0,top = 0,right = m - 1,bottom = n - 1;
        //建立返回的数组
        int[] number = new int[m * n];
        int index = 0;
        while(true){
    
    
            //从矩阵位置(0,0)开始从左到右
            for(int i = left;i <= right;i++){
    
    
                number[index++] = matrix[top][i];
            }
            //遍历完此行top值下移,直到大于bottom值
            top++;
            if(top > bottom){
    
    
                break;
            }
            //从上到下
            for(int i = top;i <= bottom;i++){
    
    
                number[index++] = matrix[i][right];
            }
            right--;
            if(right < left){
    
    
                break;
            }
            //从右到左
            for(int i = right;i >= left;i--){
    
    
                number[index++] = matrix[bottom][i];
            }
            bottom--;
            if(bottom < top){
    
    
                break;
            }
            //从下到上
            for(int i = bottom;i >= top;i--){
    
    
                number[index++] = matrix[i][left];
            }
            left++;
            if(left > right){
    
    
                break;
            }
        }
        return number;
    }
}

Guess you like

Origin blog.csdn.net/Royalic/article/details/120211126