题目
描述
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
数据范围:
0≤n,m≤10,矩阵中任意元素都满足 ∣val∣≤100
要求:空间复杂度 O(nm) ,时间复杂度 O(nm)
思路
从外围走,从左到右,从上到下,从右到左,从下到上。每走一下更新边界,直到left和right或者top和bottom重合时跳出循环。
代码
python版本:
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param matrix int整型二维数组
# @return int整型一维数组
#
class Solution:
def spiralOrder(self , matrix: List[List[int]]) -> List[int]:
# write code here
storage = []
if not len(matrix):
return storage
left =0
right = len(matrix[0])
top=0
bottom = len(matrix)
while(left<right and top<bottom):
#从左到右
for i in range(left, right):
storage.append(matrix[top][i])
top += 1
if(top==bottom):
break
#从上到下
for i in range(top, bottom):
storage.append(matrix[i][right-1])
right -= 1
if(left == right):
break
#从右到左
for i in range(right-1, left-1, -1):
storage.append(matrix[bottom-1][i])
bottom -= 1
if(top==bottom):
break
#从下到上
for i in range(bottom-1, top-1, -1):
storage.append(matrix[i][left])
if(left == right):
break
left += 1
return storage
c++版本:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> storage;
if(matrix.empty()){
return storage;
}
int top = 0;
int bottom = matrix.size();
int left = 0;
int right = matrix[0].size();
while(left<right && top<bottom){
//从左到右
for(int i=left; i<right; i++){
storage.push_back(matrix[top][i]);
}
top++;
if(top==bottom){
break;
}
//从上到下
for(int i=top; i<bottom; i++){
storage.push_back(matrix[i][right-1]);
}
right--;
if(left==right){
break;
}
//从右到左
for(int i=right-1; i>=left; i--){
storage.push_back(matrix[bottom-1][i]);
}
bottom--;
//从下到上
for(int i=bottom-1; i>=top; i--){
storage.push_back(matrix[i][left]);
}
left++;
}
return storage;
}
};