输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
开始一直想着while循环里只做一次写入的操作,这样需要考虑很多边界条件。但是向这样while里做一圈的写入操作,对于每条边的操作用for来做,省去了很多对于边界条件的考量,既简单又好用,思维不能局限。
1 class Solution { 2 public: 3 vector<int> printMatrix(vector<vector<int> > matrix) { 4 int row=matrix[0].size(); 5 int col=matrix.size(); 6 vector<int> res; 7 if(row==0) return res; 8 int left=0; 9 int right=row-1; 10 int top=0; 11 int bottom=col-1; 12 int i=0; 13 int j=0; 14 while(left<=right&&top<=bottom){ 15 for(i=left;i<=right;i++) 16 res.push_back(matrix[top][i]); 17 top++; 18 if(top>bottom) break; 19 for(i=top;i<=bottom;i++) 20 res.push_back(matrix[i][right]); 21 right--; 22 if(right<left) break; 23 for(i=right;i>=left;i--) 24 res.push_back(matrix[bottom][i]); 25 bottom--; 26 if(bottom<top) break; 27 for(i=bottom;i>=top;i--) 28 res.push_back(matrix[i][left]); 29 left++; 30 31 } 32 return res; 33 } 34 };