路徑的長度即為矩陣中的元素數量,當路徑的長度達到矩陣中的元素數量時即為完整路徑,將該路徑返回。
循環打印: “從左向右、從上向下、從右向左、從下向上” 四個方向循環打印。
class Solution:def spiralOrder(self, matrix: List[List[int]]) -> List[int]:if not matrix or not matrix[0]:return []r,c = len(matrix),len(matrix[0])res=[]left,right,top,bottom = 0,c-1,0,r-1while left<=right and top<=bottom:for i in range(left,right+1):res.append(matrix[top][i])for j in range(top+1,bottom+1):res.append(matrix[j][right])if left<right and top<bottom:for i in range(right-1,left,-1):res.append(matrix[bottom][i])for j in range(bottom,top,-1):res.append(matrix[j][left])left,right,top,bottom=left+1,right-1,top+1,bottom-1return res