landscapemi的博客

# leetcode_c++：Spiral Matrix（054）

## 题目

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

## 算法

class Solution{
public:
vector<int> spiralOrder(vector<vector<int> > &matrix){
vector<int> result;
if(matrix.empty())
return result;
int beginX=0,endX=matrix[0].size()-1;
int beginY=0,endY=matrix.size()-1;

while(true){
//from left to right
for(int i=beginX;i<=endX;++i)
result.push_back(matrix[beginY][i]);
if(++beginY>endY)  break;

//from top to down
for(int i=beginY;i<=endY;++i)
result.push_back(matrix[i][endX]);
if(beginX>--endX)  break;

//form right to left
for(int i=endX;i>=beginX;--i)
result.push_back(matrix[endY][i]);
if(beginY>--endY)  break;

//form bottom to up
for(int i=endY;i>=beginY;--i)
result.push_back(matrix[i][beginX]);
if(++beginX>endX) break;

}

return result;

}
};


#### [Leetcode]54. Spiral Matrix @python

2016-01-18 21:27:37

#### [C++]LeetCode: 110 Spiral Matrix (螺旋输出矩阵元素)

2015-01-19 16:28:56

#### LeetCode（54）Spiral Matrix

2015-09-05 21:28:57

#### 54. Spiral Matrix (重要！！！)

2016-07-17 23:01:15

#### 1105. Spiral Matrix (25) 排序、模拟

2016-04-06 14:39:28

#### 【LeetCode】59. Spiral Matrix II 解题报告

2016-05-15 11:21:35

#### 【LeetCode with Python】 Spiral Matrix II

2014-11-30 21:50:32

#### Spiral Matrix II -- LeetCode

2014-03-24 06:54:28

#### LeetCode 054 Spiral Matrix

2014-02-09 18:32:21

#### 054 - Spiral Matrix

2015-11-26 18:27:06