-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlc54. Spiral Matrix.py
42 lines (39 loc) · 1.08 KB
/
lc54. Spiral Matrix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return matrix
res = []
direcs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
d = 0
pos = [0, 0]
N = len(matrix)
M = len(matrix[0])
left, right = -1, M
top, button = -1, N
size = M * N
for i in range(size):
# print(pos[0], pos[1])
res.append(matrix[pos[0]][pos[1]])
if pos[1] + direcs[d][1] == right:
d = (d + 1) % 4
top += 1
elif pos[1] + direcs[d][1] == left:
d = (d + 1) % 4
button -= 1
elif pos[0] + direcs[d][0] == button:
d = (d + 1) % 4
right -= 1
elif pos[0] + direcs[d][0] == top:
d = (d + 1) % 4
left += 1
pos[0] += direcs[d][0]
pos[1] += direcs[d][1]
return res
nums = [
]
s = Solution()
print(s.spiralOrder(nums))