-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path54.Spiral-Matrix-v2.py
38 lines (36 loc) · 1.17 KB
/
54.Spiral-Matrix-v2.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
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
visited = -101
res = []
m, n = len(matrix), len(matrix[0])
row, col = 0, 0
while len(res) < m * n:
# go right
while col < n and matrix[row][col] != visited:
res.append(matrix[row][col])
matrix[row][col] = visited
col += 1
# go bottom
col -= 1
row += 1
while row < m and matrix[row][col] != visited:
res.append(matrix[row][col])
matrix[row][col] = visited
row += 1
# go left
row -= 1
col -= 1
while col >= 0 and matrix[row][col] != visited:
res.append(matrix[row][col])
matrix[row][col] = visited
col -= 1
# go up
col += 1
row -= 1
while row >= 0 and matrix[row][col] != visited:
res.append(matrix[row][col])
matrix[row][col] = visited
row -= 1
row += 1
col += 1
return res