Spiral Matrix

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         if(matrix.empty()) return vector<int>();
 5         
 6         int m = matrix.size();
 7         int n = matrix[0].size();
 8 
 9         vector<int> res(m*n,0);
10 
11         int x1 = 0; 
12         int y1 = 0;
13         int x2 = m - 1;
14         int y2 = n - 1;
15 
16         int num = 0;
17         while(x1 <= x2 && y1 <= y2){
18             for(int i=y1;i<=y2;i++) res[num++] = matrix[x1][i];
19             for(int i=x1+1;i<=x2;i++) res[num++] = matrix[i][y2];
20             if(x2 != x1)
21                 for(int i=y2-1;i>=y1;i--) res[num++] =matrix[x2][i];
22             if(y1 != y2)   
23                 for(int i=x2-1;i>x1;i--) res[num++] = matrix[i][y1];
24 
25             x1++,y1++,x2--,y2--;
26         } 
27         return res;
28     }
29 };

 

posted @ 2015-12-09 23:57  wxquare  阅读(178)  评论(0编辑  收藏  举报