-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathprint_matrix_in_spiral_reverse.py
64 lines (51 loc) · 1.29 KB
/
print_matrix_in_spiral_reverse.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
#!/usr/bin/python
# Date: 2018-09-22
#
# Description:
# Given a matrix, print that in reverse clockwise spiral form.
#
# Approach:
# Check on the number of elements processed keeping track of 4 boundaries - top,
# right, bottom, left
#
# Complexity:
# O(M*N) M = Rows, N = Columns
def print_matrix_in_spiral_reverse(matrix):
rows = len(matrix)
cols = len(matrix[0])
size = rows * cols
res = []
top = 0
left = 0
bottom = rows - 1
right = cols - 1
while len(res) < size:
for i in range(right, left - 1, -1):
if len(res) < size:
res.append(matrix[top][i])
top += 1
for i in range(top, bottom + 1):
if len(res) < size:
res.append(matrix[i][left])
left += 1
for i in range(left, right + 1):
if len(res) < size:
res.append(matrix[bottom][i])
bottom -= 1
for i in range(bottom, top - 1, -1):
if len(res) < size:
res.append(matrix[i][right])
right -= 1
return res
def main():
matrix = [
[1, 2, 3, 13, 23],
[4, 5, 6, 16, 26],
[7, 8, 9, 19, 29],
]
for r in matrix:
print(r)
spiral = print_matrix_in_spiral_reverse(matrix)
print(spiral)
if __name__ == '__main__':
main()