Spiral Matrix
https://leetcode.com/explore/learn/card/array-and-string/202/introduction-to-2d-array/1168/
四个指针,四种情况。其实很简单,背下来。
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
m = len(matrix)
if m == 0:
return res
n = len(matrix[0])
left = 0
right = n-1
bottom = 0
top = m-1
d = 0
while left <= right and bottom <= top:
if d == 0:
for i in range(left,right+1):
res.append(matrix[bottom][i])
bottom+=1
d=1
elif d ==1 :
for i in range(bottom,top+1):
res.append(matrix[i][right])
right-=1
d=2
elif d==2 :
for i in range(right,left-1,-1):
res.append(matrix[top][i])
top-=1
d=3
elif d == 3:
for i in range(top,bottom-1,-1):
res.append(matrix[i][left])
left+=1
d=0
return res
Last updated
Was this helpful?