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

One, foreword

You are given a matrix matrix with m rows and n columns. Please return all elements in the matrix in clockwise spiral order.

Title link: Spiral matrix I.

Two, the title requirements

Sample 1

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

The sample 2

Input: matrix = [[1, 2, 3, 4], [5,6,7,8], [9,10,11,12]] output:,2,3,4,8,12,11,10,9,5,6,7 [1]Copy the code

inspection

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

Third, problem analysis

This topic mainly investigates the idea of simulation, a more classic topic.

First of all, we will determine the direction and boundary problem, first defined as up, down, left and right four directions,

They are represented by four letters u, D, L and R

Where u=0(uppermost row), d= number of rows, L =0(leftmost column), r= number of columns.

Look at the diagram above and let’s actually simulate each of these situations

  1. 1->2->3->4 represents the direction of L -> R, where row = U, column from L ->r gradually +1, after reaching 4, turn down 8, then U drops one line, ++ U

  2. 8->12->16 represents the direction of u->d, where column =r, row from u->d gradually +1, after 16, turn left 15, so r moves left one column, –r

  3. 15->14->13 represents the direction of r-> L, where row =d, column from r-> L gradually -1, after 13, up to 9, so d moves up one row, –d

  4. 9->5 represents the direction of d->u, where column = L, row from d->u gradually -1, after reaching 5, turn right, so L moves one column to the right, ++ L

The above is the four operations inside a loop, and the judgment of the inner boundary of the loop:

  • The first step is ++u>d to exit the loop
  • Step 2 –r< L, exit the loop
  • Step 3 –d
  • Step 4 ++ L >r to exit the loop

The following code strictly corresponds to the above steps, I hope you can understand.

Four, coding implementation

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int i,u=0,d=matrix.size(a)- 1,l=0,r=matrix[0].size(a)- 1;// Determine the boundary, initialize the data
        vector<int>v;// Array storage
        while(1)// Four steps in the loop
        {
            for(i=l; i<=r; i++) v.push_back(matrix[u][i]);/ / l - > r direction
            if(++u>d) break;
            for(i=u; i<=d; i++) v.push_back(matrix[i][r]);/ / u - > d direction
            if(--r<l) break;
            for(i=r; i>=l; i--) v.push_back(matrix[d][i]);/ / r - > l direction
            if(--d<u) break;
            for(i=d; i>=u; i--) v.push_back(matrix[i][l]);/ / d - > u direction
            if(++l>r) break;
        }
        returnv; }};Copy the code

V. Test results