[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].

 

很好理解的思路。每个循环来遍历一圈。

确定圈的左上点的坐标(x1,y1)和右下点的坐标(x2,y2)。

继续遍历的条件是(x2>=x1 && y2>=y1)。

是不是很简单,也不容易错。

 1 class Solution {
 2 public:
 3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
 4         vector<int> result;
 5         if(matrix.size()==0 || matrix[0].size()==0) return result;
 6         int m=matrix.size(),n=matrix[0].size();
 7         int x1=0,y1=0,x2=m-1,y2=n-1;
 8         while(x2>=x1 & y2>=y1)
 9         {
10             if(x2>=x1 & y2>=y1)
11             {
12                 for(int i=y1;i<=y2;i++) result.push_back(matrix[x1][i]);
13                 x1++;
14             }
15             if(x2>=x1 & y2>=y1)
16             {
17                 for(int i=x1;i<=x2;i++) result.push_back(matrix[i][y2]);
18                 y2--;
19             }
20             if(x2>=x1 & y2>=y1)
21             {
22                 for(int i=y2;i>=y1;i--) result.push_back(matrix[x2][i]);
23                 x2--;
24             }
25             if(x2>=x1 & y2>=y1)
26             {
27                for(int i=x2;i>=x1;i--) result.push_back(matrix[i][y1]);
28                 y1++; 
29             }
30         }
31         return result;
32     }
33 };

 

posted @ 2015-09-09 22:31  Sean_le  阅读(199)  评论(0编辑  收藏  举报