-
Notifications
You must be signed in to change notification settings - Fork 19
/
answer.py
111 lines (88 loc) · 2.9 KB
/
answer.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/python
#------------------------------------------------------------------------------
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
result = []
if len(matrix) == 0: return result
# Limits set for spiral
hlimit = len(matrix[0])
vlimit = len(matrix) - 1
# Indexes set to keep track of the spiral
hidx = 0
vidx = 0
# Curr to count amount of times iterated
curr = 0
# Weird triggers to break loop for nonsquare arrays
# Probably a bad way to go about it, but I'm tired right now
vTrigger = True
hTrigger = True
# Each loop is one full spiral around the array
while hlimit > 0 or vlimit > 0:
## Forward
# Horizontal
if not vTrigger: break
while curr < hlimit:
result.append(matrix[vidx][hidx])
hidx += 1
curr += 1
hTrigger = True
# Sets hidx back to proper position
hidx -= 1
# Moves down for next loop
vidx += 1
hlimit -= 1
curr = 0
vTrigger = False
# Vertical
if not hTrigger: break
while curr < vlimit:
result.append(matrix[vidx][hidx])
vidx += 1
curr += 1
vTrigger = True
# Set vidx back to proper position
vidx -= 1
# Moves to the left for the next loop
hidx -= 1
vlimit -= 1
curr = 0
hTrigger = False
## Backwards
# Horizontal
if not vTrigger: break
while curr < hlimit:
result.append(matrix[vidx][hidx])
hidx -= 1
curr += 1
hTrigger = True
# Set hidx back to proper position
hidx += 1
# Moves up for the next loop
vidx -= 1
hlimit -= 1
curr = 0
vTrigger = False
# Vertical
if not hTrigger: break
while curr < vlimit:
result.append(matrix[vidx][hidx])
vidx -= 1
curr += 1
vTrigger = True
# Set vidx back to proper position
vidx += 1
# Moves right for the next loop
hidx += 1
vlimit -= 1
curr = 0
hTrigger = False
return result
#------------------------------------------------------------------------------
#Testing
def main():
print Solution().spiralOrder([[2,3]])
main()