Spiral matrix (2) solution

Spiral Matrix (2)

insert image description here

analyze:

Simulation by layer The
matrix can be regarded as several layers, first fill in the outermost element of the matrix, then fill in the second outer element of the matrix, until the innermost element of the matrix is ​​filled.
insert image description here
For each layer, fill in all elements in clockwise order starting from the top left.
Assuming that the upper left corner of the current layer is at (top, left), and the lower right corner is at (bottom, right), fill in the elements of the current layer in the following order:

  1. Fill in the upper elements from left to right, in order (top, left) to (top, right);
  2. Fill in the elements on the right from top to bottom, from (top + 1, right) to (bottom, right);
  3. Fill in the bottom elements from right to left, from (bottom, right - 1) to (bottom, left);
  4. Fill in the elements on the left from bottom to top, from (bottom - 1, left) to (top + 1, left).

After filling all the elements of the current layer, increase the left and top by 1 respectively, and decrease the right and bottom by 1 respectively, enter the next layer and continue to fill in the elements until all the elements are filled.

the code

class Solution {
    
    
    public int[][] generateMatrix(int n) {
    
    
        int num = 1;
        int[][] matrix = new int[n][n];
        int top = 0, right = n - 1, bottom = n - 1, left = 0;
        while(left <= right && top <= bottom) {
    
    
            for(int col = top; col <= right; col++) {
    
    
                matrix[top][col] = num;
                num++;
            }
            for(int row = top + 1; row <= bottom; row++) {
    
    
                matrix[row][right] = num;
                num++;
            }
            for(int col = right - 1; col >= top; col--) {
    
    
                matrix[bottom][col] = num;
                num++;
            }
            for(int row = bottom - 1; row > top; row--) {
    
    
                matrix[row][left] = num;
                num++;
            }
            top++;
            right--;
            bottom--;
            left++;
        }
        return matrix;
    }
}

Guess you like

Origin blog.csdn.net/weixin_45832482/article/details/122714522