Description
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]
分析
题目的意思是:螺旋输出m*n矩阵的值。
- 常规的矩阵遍历做法,其中要注意矩阵判空,然后遍历矩阵的时候要考虑矩阵的行和列只有一行的情况。
C++代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.size()==0){
return res;
}
int rows=matrix.size()-1;
int cols=matrix[0].size()-1;
int row=0;
int col=0;
while(row<=rows&&col<=cols){
for(int i=col;i<=cols;i++){
res.push_back(matrix[row][i]);
}
row++;
for(int i=row;i<=rows;i++){
res.push_back(matrix[i][cols]);
}
cols--;
if(row<=rows){
for(int i=cols;i>=col;i--){
res.push_back(matrix[rows][i]);
}
}
rows--;
if(col<=cols){
for(int i=rows;i>=row;i--){
res.push_back(matrix[i][col]);
}
}
col++;
}
return res;
}
};
Python 代码
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
rows = len(matrix)-1
cols = len(matrix[0])-1
row=0
col=0
res=[]
while(row<=rows and col<=cols):
for j in range(col,cols+1):
res.append(matrix[row][j])
row+=1
for i in range(row,rows+1):
res.append(matrix[i][cols])
cols-=1
if row<=rows:
for j in range(cols,col-1,-1):
res.append(matrix[rows][j])
rows-=1
if col<=cols:
for i in range(rows,row-1,-1):
res.append(matrix[i][col])
col+=1
return res