面试150 螺旋矩阵
思路
模拟法。从左到右,从上到下,从右到左,从下到上四个方向进行遍历模拟。
class Solution:def spiralOrder(self, matrix: List[List[int]]) -> List[int]:if not matrix:return []res=[] #存放结果m=len(matrix)n=len(matrix[0])left=0top=0right=n-1bottom=m-1while left<=right and top<=bottom:for i in range(left,right+1):res.append(matrix[top][i])top+=1for i in range(top,bottom+1):res.append(matrix[i][right])right-=1if top<=bottom:for i in range(right,left-1,-1):res.append(matrix[bottom][i])bottom-=1if left<=right:for i in range(bottom,top-1,-1):res.append(matrix[i][left])left+=1return res