【leetcode】 Spiral Matrix

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 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 class Solution {
 6 public:
 7     vector<int> spiralOrder(vector<vector<int> > &matrix) {
 8         vector<int> ans;
 9         if(matrix.empty())
10             return ans;
11         int begin_row = 0, end_row = matrix[0].size() - 1;//begin_row is the row number, end_row is the remaind size of each row
12         int begin_col = 0, end_col = matrix.size() - 1;//begin_col is the col number,end_col is the remaind size of each col
13         while(true){
14             for(int i = begin_row; i <= end_row; ++i)//left to right
15                 ans.push_back(matrix[begin_row][i]);
16             if(++begin_col > end_col) break;
17 
18             for(int i = begin_col; i <= end_col; ++i)//up to down
19                  ans.push_back(matrix[i][end_row]);
20             if(begin_row > --end_row) break;
21 
22             for(int i = end_row; i >= begin_row; --i)//right to left
23                 ans.push_back(matrix[end_col][i]);
24             if(begin_col > --end_col) break;
25 
26             for(int i = end_col; i >= begin_col; --i)//bottom to up
27                 ans.push_back(matrix[i][begin_row]);
28             if(++begin_row > end_row) break;
29         }
30         return ans;
31     }
32 };
33 
34 
35 
36 int main()
37 {
38     Solution s;
39     vector<vector<int> > matrix;
40     vector<int> v;
41     for(int i = 1; i <=9; i++){
42         v.push_back(i);
43         if(i % 3 == 0){
44             matrix.push_back(v);
45             v.clear();
46         }
47     }
48     vector<int> ans = s.spiralOrder(matrix);
49     for(int i = 0; i < ans.size(); ++i)
50         cout<< ans[i] <<endl;
51     return 0;        
52 }

 

posted @ 2015-02-07 15:45  neuzxy  阅读(178)  评论(0编辑  收藏  举报