-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path29_PrintMatrix.py
39 lines (31 loc) · 872 Bytes
/
29_PrintMatrix.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
def print_matrix(matrix):
if not matrix:
return
res = []
top, down, left, right = 0, len(matrix)-1, 0, len(matrix[0])-1
while True:
for i in range(left, right+1):
res.append(matrix[top][i])
top += 1
if top >down:
break
for i in range(top, down+1):
res.append(matrix[i][right])
right -= 1
if left >right:
break
for i in range(right, left - 1, -1):
res.append(matrix[down][i])
down -= 1
if top > down:
break
for i in range(down, top - 1, -1):
res.append(matrix[i][left])
left += 1
if left >right:
break
return res
if __name__ == '__main__':
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
res = print_matrix(matrix)
print(res)