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

给定m × n个元素(m行,n列)的矩阵,按照螺旋顺序返回矩阵的所有元素。

例如,给定以下矩阵:

[ 
 [1,2,3],
 [4,5,6],
 [7,8,9] 
]

你应该返回[1,2,3,6,9,8,7,4,5]

(1)思想1:顺着spiralorder剥皮,up->right->bottom->left. 用四个变量x1, x2, y1, y2 控制上下左右边界。注意循环条件为x1<=x2 && y1<= y2,另外注意每行和每列输出的范围,代码如下:

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

 

posted @ 2017-12-07 10:21  西瓜刀刀刀  阅读(127)  评论(0编辑  收藏  举报