题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:
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 vector<int> printMatrix(vector<vector<int> > matrix) { 4 vector<int> result; 5 if (matrix.size() == 0) 6 return result; 7 int len1 = matrix[0].size(); 8 int len2 = matrix.size() -1; 9 int j,i = 0; 10 for ( j = 0; j < len1 ; ++j) 11 { 12 result.push_back(matrix[i][j]); 13 } 14 --len1; 15 --j; 16 while(len1 >= 0 && len2 >= 0) 17 { 18 for(int k = 0 ; k < len2 ; ++k) 19 { 20 ++ i; 21 result.push_back(matrix[i][j]); 22 } 23 --len2; 24 if (len2 <0) 25 break; 26 27 for(int k = 0 ; k < len1 ; ++k) 28 { 29 -- j; 30 result.push_back(matrix[i][j]); 31 } 32 --len1; 33 if (len1 <0) 34 break; 35 36 37 for(int k = 0 ; k < len2 ; ++k) 38 { 39 -- i; 40 result.push_back(matrix[i][j]); 41 } 42 43 --len2; 44 if (len2 <0) 45 break; 46 47 for(int k = 0 ; k < len1 ; ++k) 48 { 49 ++ j; 50 result.push_back(matrix[i][j]); 51 } 52 53 --len1; 54 if (len1 <0) 55 break; 56 } 57 return result; 58 } 59 };