forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiral_matrix.py
More file actions
75 lines (58 loc) · 1.46 KB
/
spiral_matrix.py
File metadata and controls
75 lines (58 loc) · 1.46 KB
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
'''
Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
=========================================
Simulate spiral moving, start from (0,0) and when a border is reached change the X or Y direction.
Time Complexity: O(N*M)
Space Complexity: O(N*M)
'''
############
# Solution #
############
def spiral_matrix(matrix):
n = len(matrix)
if n == 0:
return []
m = len(matrix[0])
if m == 0:
return []
total = n * m
res = []
n -= 1
xDir, yDir = 1, 1
x, y = 0, -1
while len(res) < total:
for i in range(m):
y += yDir
res.append(matrix[x][y])
m -= 1 # decrease horizontal moving steps
yDir *= -1 # change the Y direction
for i in range(n):
x += xDir
res.append(matrix[x][y])
n -= 1 # decrease vertical moving steps
xDir *= -1 # change the Y direction
return res
###########
# Testing #
###########
# Test 1
# Correct result => [1, 2, 3, 6, 9, 8, 7, 4, 5]
print(spiral_matrix([[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]))
# Test 2
# Correct result => [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
print(spiral_matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))