题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
思路:由外向里,按圈打印,考虑最后一圈退化为一行或一列或一个点
1 class Solution { 2 public: 3 void myPrint(vector<vector<int> > &matrix, int i, int j, int m, int n, vector<int> &res) 4 { 5 if(i>m || j>n)return; 6 if(i==m) 7 { 8 for(; j<=n; ++j)res.push_back(matrix[i][j]); 9 return; 10 } 11 if(j==n) 12 { 13 for(; i<=m; ++i)res.push_back(matrix[i][j]); 14 return; 15 } 16 for(int idx=j; idx<n; ++idx)res.push_back(matrix[i][idx]); 17 for(int idx=i; idx<m; ++idx)res.push_back(matrix[idx][n]); 18 for(int idx=n; idx>j; --idx)res.push_back(matrix[m][idx]); 19 for(int idx=m; idx>i; --idx)res.push_back(matrix[idx][j]); 20 myPrint(matrix, i+1, j+1, m-1, n-1, res); 21 } 22 vector<int> printMatrix(vector<vector<int> > matrix) { 23 vector<int> res; 24 if(matrix.size()==0 || matrix[0].size()==0)return res; 25 int row=matrix.size(); 26 int col=matrix[0].size(); 27 myPrint(matrix, 0, 0, row-1, col-1, res); 28 return res; 29 } 30 };