-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path54_Spiral_Matrix.py
97 lines (73 loc) · 2.48 KB
/
54_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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
# Time Complexity O(n) and Space Complexity is O(n)
row = len(matrix)
col = len(matrix[0])
n = row*col
direction = True # row, False : column
sign = True # for incressing , False : decressing
c = 0
r = 0
ans = []
visited = [[-1 for _ in range(col)] for _ in range(row)]
for i in range(n):
if direction:
ans.append(matrix[r][c])
visited[r][c] = 1
if sign:
c +=1
else:
c -=1
if c == col:
direction = False
c -=1
r +=1
elif c<0 and r>0:
r -= 1
c = 0
direction = False
sign = False
if i == n-1:
continue
if visited[r][c] != -1:
if sign is True:
r +=1
c -=1
direction = False
else:
#print(r, c)
r -=1
c +=1
#print(r, c)
direction = False
sign = False
else:
ans.append(matrix[r][c])
visited[r][c]=1
if sign:
r+=1
else:
r-=1
if r == row:
r-=1
c-=1
direction=True
sign=False
if i == n-1:
continue
if visited[r][c] != -1:
if sign is True:
r-=1
c -=1
direction = True
sign = False
else:
r +=1
c +=1
direction = True
sign = True
return ans