LeetCode 54. Spiral Matrix (Spiral Matrix) refers to the offer- clockwise printing matrix

 

Topic description

 

Given a  matrix of m x n  elements ( m rows, n columns), return all elements in the matrix in a clockwise spiral order.

 

Example 1:

enter:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

 

Example 2:

enter:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

 

Problem solving ideas

 

First, determine whether the coordinates of the upper left corner element of the outer circle of the matrix to be printed meet the conditions. It can be seen by observation that twice the abscissa and ordinate of the upper left element should be smaller than the total number of rows and columns respectively, that is, row*2<rows and col*2<cols. Then judge the printing boundary situation, you can get the rightmost column index as cols-col-1, and similarly the bottom row index is rows-row-1, consider printing and checking in the following order:

  • Starting from the upper left element, print the first row to the rightmost column;
  • Starting from the rightmost column element of the second row, print the last column to the most row;
  • If the bottom row index does not coincide with the first row, start from the penultimate column element of the bottom row, and print the element to the first column;
  • If the leftmost row index does not coincide with the rightmost row, start from the penultimate row element of the first column, and print to the second row to stop

 

code

 

 1 class Solution {
 2 public:
 3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
 4         vector<int> v;
 5         if(matrix.empty())
 6             return v;
 7         int rows=matrix.size(),cols=matrix[0].size();
 8         int row=0,col=0;
 9         while(row*2<rows&&col*2<cols){
10             int rl=rows-row-1,cl=cols-col-1;
11             for(int i=col;i<=cl;i++)
12                 v.push_back(matrix[row][i]);
13             for(int i=row+1;i<=rl;i++)
14                 v.push_back(matrix[i][cl]);
15             if(rl!=row){
16                 for(int i=cl-1;i>=col;i--)
17                     v.push_back(matrix[rl][i]);
18             }
19             if(cl!=col){
20                 for(int i=rl-1;i>row;i--)
21                     v.push_back(matrix[i][col]);
22             }
23             row++;col++;
24         }
25         return v;
26     }
27 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325519540&siteId=291194637