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 };
原文:http://www.cnblogs.com/xiaoyesoso/p/5149668.html