forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspiralmatrix.py
39 lines (30 loc) · 1.04 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
def spiral_order(matrix):
result = []
if not matrix:
return result
rows, cols = len(matrix), len(matrix[0])
top, bottom, left, right = 0, rows - 1, 0, cols - 1
while top <= bottom and left <= right:
# Traverse from left to right
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1
# Traverse from top to bottom
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
if top <= bottom:
# Traverse from right to left
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1
if left <= right:
# Traverse from bottom to top
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
return result
# Example usage:
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
result = spiral_order(matrix)
print(" ".join(map(str, result)))