- 分类:Array
- 时间复杂度: O(n*m)
54. Spiral Matrix
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:
def spiralOrder(self, matrix: 'List[List[int]]') -> 'List[int]':
res=[]
if matrix==None or matrix==[] or matrix==[[]]:
return res
top=0
left=0
right=len(matrix[0])-1
bottom=len(matrix)-1
row,col=0,0
while left<right and top<bottom:
while col<right:
res.append(matrix[row][col])
col+=1
while row<bottom:
res.append(matrix[row][col])
row+=1
while col>left:
res.append(matrix[row][col])
col-=1
while row>top:
res.append(matrix[row][col])
row-=1
top+=1
left+=1
col+=1
row+=1
right-=1
bottom-=1
if left==right and top==bottom:
res.append(matrix[top][left])
elif top==bottom:
while left<=right:
res.append(matrix[top][left])
left+=1
elif left==right:
while top<=bottom:
res.append(matrix[top][left])
top+=1
return res
讨论:
1.最后剩余的这三种情况最重要,要进行分类讨论=。=
2.col和row别忘了+1
网友评论