-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiralMatrix.py
More file actions
31 lines (24 loc) · 1.23 KB
/
Copy pathspiralMatrix.py
File metadata and controls
31 lines (24 loc) · 1.23 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
class Solution:
# Recursive solution
# def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
# return list(matrix[0]) + self.spiralOrder(list(zip(*matrix[1:]))[::-1]) if matrix else []
# take the first row + rotate the rest of the matrix counter-clockwise and repeat
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
left_border, up_border, right_border, down_border = 0, 0, len(matrix[0]), len(matrix)
result = []
while (left_border < right_border and up_border < down_border):
for i in range(left_border, right_border):
result.append(matrix[up_border][i])
up_border += 1
for i in range(up_border, down_border):
result.append(matrix[i][right_border-1])
right_border -= 1
if not (left_border < right_border and up_border < down_border):
return result
for i in range(right_border-1, left_border-1, -1):
result.append(matrix[down_border-1][i])
down_border -= 1
for i in range(down_border-1, up_border-1, -1):
result.append(matrix[i][left_border])
left_border += 1
return result