Algorithm questions daily practice---Day 65: Spiral Matrix II

Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-In Event, click to view the event details .

1. Problem description

Given a positive integer  n , generate a   square matrix  containing 1 all  n2 elements in a spiral arranged in clockwise order   .n x nmatrix

Topic link: Spiral Matrix II .

Second, the subject requirements

Example 1

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

Example 2

输入: n = 1
输出: [[1]]
复制代码

visit

1.模拟计算
2.建议用时15~35min
复制代码

3. Problem Analysis

This question is essentially the same as the Algorithm Question Daily Practice --- Day 64: Spiral Matrix I.

It's just the first question that gives you the array and lets you output. The second question gives you ranges and lets you output arrays. It is recommended that you do the 螺旋矩阵 Iquestion (the explanation is more detailed), and then come back and do this question to consolidate the relevant knowledge.

Fourth, the encoding implementation

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int k=1,i,u=0,d=n-1,l=0,r=n-1;//初始化数据,定义上下左右四个方向范围
        vector<vector<int>>v(n, vector<int>(n));//定义二维数组
        while(1)//循环判断
        {
            for(i=l;i<=r;i++) v[u][i]=k++;//l->r方向
            if(++u>d) break;
            for(i=u;i<=d;i++) v[i][r]=k++;//u->d方向
            if(--r<l) break;
            for(i=r;i>=l;i--) v[d][i]=k++;//r->方向
            if(--d<u) break;
            for(i=d;i>=u;i--) v[i][l]=k++;//d->u方向
            if(++l>r) break;
        }
        return v;

    }
};
复制代码

5. Test results

4.png

5.png

Guess you like

Origin juejin.im/post/7080686157725433892