1 class Solution: 2 def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 3 m, n = len(matrix), len(matrix[0]) 4 res = [] #存放遍历后的结果 5 startx = starty = 0 6 7 for offset in range(min(m, n)//2): #offset初始值为0 左闭右开 range(1,1):不循环了 8 9 for j in range(starty, n-offset-1): #从左到右 10 res.append(matrix[startx][j]) 11 12 for i in range(startx, m-offset-1):#从上到下 13 res.append(matrix[i][n-offset-1]) 14 15 for j in range(n-offset-1, starty,-1):#从右到左 16 res.append(matrix[m-offset-1][j]) 17 18 for i in range(m-offset-1,startx, -1): #从下到上 19 res.append(matrix[i][starty]) 20 21 startx += 1 22 starty += 1 23 24 if min(m, n) % 2 == 1: 25 offset = min(m, n) // 2 26 if m <= n: 27 for j in range(offset, n-offset): 28 res.append(matrix[offset][j]) 29 else: 30 for i in range(offset, m-offset): 31 res.append(matrix[i][n-offset-1]) 32 33 return res
标签:章节,startx,starty,res,matrix,54,range,offset,进阶 From: https://www.cnblogs.com/wuyijia/p/17660883.html