forked from thatguyintech/100-day-coding-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspiralMatrix.py
58 lines (48 loc) · 1.38 KB
/
spiralMatrix.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
def spiralMatrixArr(matrix):
direction = 0
# boundaries
top, left = 0, 0
right = len(matrix[0]) # row/width
bottom = len(matrix) # column/height
# starting coordinates
row, col = 0, 0
# for testing
ret = []
while top < bottom and left < right:
# go right
while col < right:
ret.append(matrix[row][col])
col += 1
top += 1
col -= 1
# go down
row += 1
while row < bottom:
ret.append(matrix[row][col])
row += 1
right -= 1
row -= 1
# go left
col -= 1
while col >= left and top < bottom:
ret.append(matrix[row][col])
col -= 1
bottom -= 1
col += 1
# go up
row -= 1
while row >= top and left < right:
ret.append(matrix[row][col])
row -= 1
row += 1
left += 1
col += 1
return ret
def tests():
matrix = [[1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [ 13, 14, 15, 16]]
assert(spiralMatrixArr(matrix) == [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10])
assert(spiralMatrixArr([[]]) == [])
assert(spiralMatrixArr([[1,2]]) == [1, 2])
assert(spiralMatrixArr([[1],[2],[3],[4]]) == [1, 2, 3, 4])
assert(spiralMatrixArr([[1,2],[8,3],[7,4],[6,5]]) == [1,2,3,4,5,6,7,8])
tests()