题目:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
螺旋生成数组
我们设四个变量,分别代表上,下,左和右
首先我们从左往右遍历,遍历完,上的位置需要下降一行,
然后从上往下遍历,遍历完,右的位置需要往左移一行,
然后从右往左遍历,遍历完,下的位置需要往上移一行,
最后从下往上遍历,遍历完,左的位置需要往右移一行
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.empty() || matrix[0].empty()) return res;
int m = matrix.size();
int n = matrix[0].size();
int up = 0, down = m -1;
int left = 0, right = n -1;
while(true){
for(int j = left; j <= right; ++j) res.push_back(matrix[up][j]);
if(++up > down) break;
for(int i = up; i <= down; ++i) res.push_back(matrix[i][right]);
if(--right < left) break;
for(int j = right; j >= left; --j) res.push_back(matrix[down][j]);
if(--down < up) break;
for(int i = down; i >= up; --i) res.push_back(matrix[i][left]);
if(++left > right) break;
}
return res;
}
};
java:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if(matrix.length == 0 || matrix[0].length == 0) return res;
int m = matrix.length;
int n = matrix[0].length;
int up = 0, down = m -1;
int left = 0, right = n -1;
while(true){
for(int j = left; j <= right; ++j) res.add(matrix[up][j]);
if(++up > down) break;
for(int i = up; i <= down; ++i) res.add(matrix[i][right]);
if(--right < left) break;
for(int j = right; j >= left; --j) res.add(matrix[down][j]);
if(--down < up) break;
for(int i = down; i >= up; --i) res.add(matrix[i][left]);
if(++left > right) break;
}
return res;
}
}
python:
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
res = []
if not matrix or not matrix[0]: return res
m = len(matrix)
n = len(matrix[0])
up = 0
down = m -1
left = 0
right = n -1
while True:
for j in xrange(left,right+1): res.append(matrix[up][j])
up += 1
if up > down: break
for i in xrange(up,down+1): res.append(matrix[i][right])
right -= 1
if right < left: break
for j in xrange(right,left-1,-1): res.append(matrix[down][j])
down -= 1
if down < up: break
for i in xrange(down, up-1,-1): res.append(matrix[i][left])
left += 1
if left > right: break;
return res