leetcode/54-240608-pass/main.py
2024-06-08 17:13:50 +02:00

32 lines
986 B
Python

class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
d = [(0,1),(1,0),(0,-1),(-1,0)]
cur_d = 0
width = len(matrix[0])
height = len(matrix)
m, n = width, height - 1
cur_m, cur_n = 0,0
cur_p = (0,0)
rlt = []
for i in range(width * height):
# print(cur_p, m, n, cur_m, cur_n)
row = cur_p[0]
col = cur_p[1]
rlt.append(matrix[row][col])
if cur_d % 2 == 0:
cur_m += 1
if cur_m == m:
m -= 1
cur_d += 1
cur_d %= 4
cur_m = 0
else:
cur_n += 1
if cur_n == n:
n -= 1
cur_d += 1
cur_d %= 4
cur_n = 0
cur_p = (row + d[cur_d][0], col+d[cur_d][1])
return rlt