题目描述:
Given a matrix of m x n elements (m rows, n columns),
return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
代码:
1 class Solution {
2 public:
3 vector<int> spiralOrder(vector<vector<int> > &matrix) {
4
5 vector<int> ret;
6 if(matrix.size()==0 || matrix[0].size() == 0)
7 return ret;
8 int m = matrix.size();
9 int n = matrix[0].size();
10 int circles=min(m,n)/2;
11 for(int i=0;i<circles;i++)
12 {
13 for(int j=i;j<=n-1-i;j++)
14 ret.push_back(matrix[i][j]);
15 for(int j=i+1;j<=m-1-i;j++)
16 ret.push_back(matrix[j][n-1-i]);
17 for(int j=n-1-i-1;j>=i;j--)
18 ret.push_back(matrix[m-1-i][j]);
19 for(int j=m-1-i-1;j>=i+1;j--)
20 ret.push_back(matrix[j][i]);
21 }
22
23 if(min(m,n)%2)
24 {
25 if(m>n)
26 {
27 for(int j=circles;j<=m-1-circles;j++)
28 ret.push_back(matrix[j][circles]);
29 }
30 else
31 {
32 for(int j=circles;j<=n-1-circles;j++)
33 ret.push_back(matrix[circles][j]);
34 }
35
36 }
37
38 return ret;
39 }
40 };