-
Notifications
You must be signed in to change notification settings - Fork 0
/
q54_Spiral_Matrix.py
67 lines (64 loc) · 1.65 KB
/
q54_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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
i,j=0,n-1
spiral = matrix[0]
direction = 1
k = 1 # number of circle
for _ in range((m - 1) * n):
if direction == 0: # right
j += 1
if j == n - k:
direction = 1
elif direction == 1: # down
i += 1
if i == m - k:
direction = 2
elif direction == 2: # left
j -= 1
if j == -1 + k:
direction = 3
elif direction == 3:
i -= 1
if i == k:
direction = 0
k += 1
spiral.append(matrix[i][j])
return spiral
def spiralOrder1(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
spiral = matrix[0]
i, j = 0, n - 1
dirs = [[1, 0], [0, -1], [-1, 0], [0, 1]]
d = 0
k = n * (m - 1)
while k > 0:
for _ in range(m - 1):
i += dirs[d][0]
j += dirs[d][1]
spiral.append(matrix[i][j])
k -= 1
m -= 1
m, n = n, m
d = (d + 1) % 4
return spiral
matrix = [
[13],
[4],
[7]
]
print(Solution().spiralOrder1(matrix))