[Code Random Thoughts | Leetcode | Day 4] Array | Spiral Matrix | 59

foreword

Welcome to Little K 's Leetcode | Code Random Records | Thematic column, today I will share with you the spiral matrix✨


59. Spiral Matrix II

Given a positive integer n, generate a square matrix containing all elements from 1 to n 2 , and the elements are spirally arranged in clockwise order .n x n matrix

Example 1:
insert image description here

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

Example 2:

输入:n = 1
输出:[[1]]

hint:

1 <= n <= 20

Ideas:

This type of topic actually does not involve any algorithm, it is to simulate the process of printing in spiral order, let's simulate it below

  • Fill upper row left to right
  • Fill right column top to bottom
  • Fill descending row from right to left
  • Fill left column from bottom to top

But we can see that there are a lot of boundary conditions in such a circle of simulation, and it is easy to make mistakes. At this time, the loop invariant rule used in the dichotomy we learned in the first section is very important.

The four sides of the matrix are either left-closed and right-open, or left-open and right-closed
insert image description here
insert image description here

class Solution {
    
    
public:
    vector<vector<int>> generateMatrix(int n)
    {
    
    
        vector<vector<int>> res(n,vector<int>(n,0));
        int startx=0,starty=0;  //定义每循环一个圈的起始位置
        int loop=n/2; //每个圈循环几次,如果n为奇数3,那么loop=1,只循环一圈
        int mid=n/2;  //矩阵中间位置,例如n为3,中间的位置为【1,1】
        int count=1;  //用来给矩阵元素赋值的
        int offset=1; //用来控制循环遍历长度
        int i,j;
        while(loop--)
        {
    
    
            i=startx,j=starty;
            //左闭右开
            for(j=starty;j<starty+n-offset;j++) res[startx][j]=count++;
            for(i=startx;i<startx+n-offset;i++) res[i][j]=count++;
            for(;j>starty;j--) res[i][j]=count++;
            for(;i>startx;i--) res[i][j]=count++;
            //第二圈开始,起始位置要各自加一
            startx++,starty++;
            offset+=2;
        }
        //如果n为奇数,则需要单独给矩阵之间的位置赋值
        if(n%2) res[mid][mid]=count;
        return res;
    }
   
};

The simulation process has been explained in detail in the above code, and here are the following two points in particular:

  • starty+n-offset: Why is the starting position added here, because the starting coordinate of the second circle is not 0
  • offset+=2: Why add 2, because the elements at both ends are missing every time you walk around, and the initial value is 1 because it follows the principle of left closing and right opening
  • There are 3 3 and 4 4 simulation diagrams on it

Summarize

✨To do this type of topic, you need to draw more simulations. It’s easy to think clearly, and pay attention to the boundary conditions (follow the rules of loop invariance)

Guess you like

Origin blog.csdn.net/qq_72157449/article/details/131745498