Sword refers to offer 29. Print matrix clockwise

Sword refers to offer 29. Print matrix clockwise

Title description

Insert picture description here

Problem-solving ideas

For each layer, traverse all elements in a clockwise order from the top left. After traversing the elements of the current layer, increase left and top by 1, respectively, decrease right and bottom by 1, enter the next layer and continue traversal until traversal End all elements.

Insert picture description here
Note that there is a pit!

Due to the loop condition while (left <= right && top <= bottom), if the current layer has only one column (left == right) or only one row (top == bottom), only the upper and right borders need to be printed, otherwise repeated printing will occur .

class Solution {
    
    
    public int[] res;

    public int[] spiralOrder(int[][] matrix) {
    
    
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return new int[0];
        //每一层的上下左右四个边界,从最外层开始
        int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
        int[] res = new int[matrix.length * matrix[0].length];
        int idx = 0;   //res数组的指针

        while (left <= right && top <= bottom) {
    
    
            //上边界:(top, left) ~ (top, right)
            for (int i = left; i <= right; i++) res[idx++] = matrix[top][i];
            //右边界:(top + 1, right) ~ (bottom, right)
            for (int i = top + 1; i <= bottom; i++) res[idx++] = matrix[i][right];
            //注意!如果该层仅有一列或仅有一行,则只需打印上边界和右边界,否则会出现重复打印
            if(left == right || top == bottom) break;
            //下边界:(bottom, right - 1) ~ (bottom, left)
            for (int i = right - 1; i >= left; i--) res[idx++] = matrix[bottom][i];
            //左边界:(bottom -  1, left) ~ (top + 1, left)
            for (int i = bottom - 1; i >= top + 1; i--) res[idx++] = matrix[i][left];
            //进入下一层
            left++; right--; top++; bottom--;
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/cys975900334/article/details/115079631