leetcode:螺旋矩陣

xiaoxinlong發表於2024-10-19

2024-10-19

https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-interview-150

 1 class Solution:
 2     def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
 3 
 4         m = len(matrix)
 5         n = len(matrix[0])
 6 
 7         u = 0
 8         d = m - 1
 9         l = 0
10         r = n - 1
11 
12         ans = []
13 
14         while(True):
15             for i in range(l,r+1):
16                 ans.append(matrix[u][i])
17             u += 1
18             if(u>d): break
19             for i in range(u,d+1):
20                 ans.append(matrix[i][r])
21             r -= 1
22             if(r<l): break
23             for j in range(l,r+1):
24                 ans.append(matrix[d][r+l-j])
25             d -= 1
26             if(u>d): break
27             for i in range(u,d+1):
28                 ans.append(matrix[d+u-i][l])
29             l += 1
30             if(l>r): break
31         
32         return ans

相關文章