问题描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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。
解题思路
以四个变量up,down,right,left表示当前输出情况,一旦up>down,left>right则表示已输出完。
c++代码
1 class Solution { 2 public: 3 vector<int> printMatrix(vector<vector<int> > matrix) { 4 vector<int> ans; 5 int up = 0, left = 0; 6 int down = matrix.size()-1; 7 int right = matrix[0].size()-1; 8 9 10 while(true){ 11 for(int i = left; i <= right; i++) 12 ans.push_back(matrix[up][i]); 13 up++; 14 if(up > down) break; 15 16 for(int i = up; i <= down; i++) 17 ans.push_back(matrix[i][right]); 18 right--; 19 if(right < left) break; 20 21 for(int i = right; i >= left; i--) 22 ans.push_back(matrix[down][i]); 23 down--; 24 if(down < up) break; 25 26 for(int i = down; i >= up; i--) 27 ans.push_back(matrix[i][left]); 28 left++; 29 if(left > right) break; 30 } 31 return ans; 32 33 } 34 };