[Simulation] | 40. Print matrix clockwise

Title description

Enter a matrix and print out each number in clockwise order from the outside to the inside.

Sample
input:

[
  [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]

Code

class Solution {
    
    
private:
    vector<int> ans;
    int r,c;
    
public:
    vector<int> printMatrix(vector<vector<int> > m) {
    
    
        r=m.size();
        if (r==0) return ans;   "陷阱,防止矩阵m为空的情况"
        c=m[0].size();  "如果矩阵为空,执行这一句就会出错"
        
        int num=min(r,c)/2;
        r--,c--; //与下标对应,但与实际含义不对应了
        for (int k=0;k<num;k++) {
    
    
            for (int j=k;j<=c-k;j++)  ans.push_back(m[k][j]);
            for (int i=k+1;i<=r-k;i++) ans.push_back(m[i][c-k]);
            for (int j=c-k-1;j>=k;j--) ans.push_back(m[r-k][j]);
            for (int i=r-k-1;i>k;i--) ans.push_back(m[i][k]); 
        }
        if (c>=r && (r+1)%2)//列数大于行数,且行数为奇数的情况
          for (int j=num;j<=c-num;j++) ans.push_back(m[num][j]);
        if (r>c && (c+1)%2) //行数大于列数,且列数为奇数的情况
          for (int i=num;i<=r-num;i++) ans.push_back(m[i][num]);
        return ans;
    }
};

Key points: Processing of
[1,2,3,4]1 row and n columns and [[1],[2],[3],[4]]n rows and 1 column

One circle and one circle, the number of cycles depends on the minimum of the number of rows and the number of columns,

If the minimum value is an odd number, only one of the above two cases will remain in the end, depending on whether the number of rows is large or the number of columns is large. If it is the same size, only one position is left.

If the minimum value is an even number, the above two situations will not occur.

Guess you like

Origin blog.csdn.net/HangHug_L/article/details/114679962