标签:
代码:
1 #include<iostream> 2 #include<vector> 3 4 using namespace std; 5 6 vector<int> spiralOrder(vector<vector<int>>& matrix) 7 { 8 if (matrix.size() == 0) 9 return vector<int>(); 10 vector<int> result; 11 int m = matrix.size(); 12 int n = matrix[0].size(); 13 int total = m*n; 14 int t = 1; 15 int k = 0; 16 while (1) 17 { 18 int i = k; 19 int j = k; 20 while (j < n - k) 21 result.push_back(matrix[i][j++]); 22 j--; 23 i++; 24 if (result.size() == total) 25 return result; 26 while (i < m - k) 27 result.push_back(matrix[i++][j]); 28 i--; 29 j--; 30 if (result.size() == total) 31 return result; 32 while (j>=k) 33 result.push_back(matrix[i][j--]); 34 j++; 35 i--; 36 while (i>k) 37 result.push_back(matrix[i--][j]); 38 if (result.size() == total) 39 return result; 40 k++; 41 } 42 } 43 44 int main() 45 { 46 vector<vector<int>> matrix = 47 { 48 {1,2,3}, 49 {4,5,6}, 50 {7,8,9} 51 }; 52 vector<int> a = spiralOrder(matrix); 53 for (int i = 0; i < a.size(); i++) 54 cout << a[i] << " "; 55 cout << endl; 56 return 0; 57 }
标签:
原文地址:http://www.cnblogs.com/chaiwentao/p/4613649.html