Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

I. Problem description

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

Title link: Spiral matrix II.

Two, the title requirements

Sample 1

Input: n = 3 output: [[1,2,3],[8,9,4],[7,6,5]]Copy the code

The sample 2

Input: n = 1 Output: [[1]]Copy the code

inspection

1. Analog calculation 2. The recommended time is 15 to 35 minutesCopy the code

Third, problem analysis

The spiral matrix I is essentially the same.

It’s just that the first one gives you an array to output. The second problem gives you a range and tells you to output an array. I suggest you do spiral matrix I first, and then come back and do it again to consolidate your knowledge.

Four, coding implementation

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int k=1,i,u=0,d=n- 1,l=0,r=n- 1;// Initialize the data, define the up, down, left and right directions of the range
        vector<vector<int>>v(n, vector<int>(n));// Define a two-dimensional array
        while(1)// loop judgment
        {
            for(i=l; i<=r; i++) v[u][i]=k++;/ / l - > r direction
            if(++u>d) break;
            for(i=u; i<=d; i++) v[i][r]=k++;/ / u - > d direction
            if(--r<l) break;
            for(i=r; i>=l; i--) v[d][i]=k++;/ / r - > direction
            if(--d<u) break;
            for(i=d; i>=u; i--) v[i][l]=k++;/ / d - > u direction
            if(++l>r) break;
        }
        returnv; }};Copy the code

V. Test results