码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Spiral Matrix

时间:2015-09-10 00:26:59      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

[LeetCode]Spiral Matrix

标签:

原文地址:http://www.cnblogs.com/Sean-le/p/4796203.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!