-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path26.py
37 lines (23 loc) · 943 Bytes
/
26.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
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []
if not matrix:
return result
m, n = len(matrix), len(matrix[0])
rowBegin, rowEnd, colBegin, colEnd = 0, m - 1, 0, n - 1
while rowBegin <= rowEnd and colBegin <= colEnd:
for i in range(colBegin, colEnd + 1):
result.append(matrix[rowBegin][i])
rowBegin += 1
for i in range(rowBegin, rowEnd + 1):
result.append(matrix[i][colEnd])
colEnd -= 1
if rowBegin <= rowEnd:
for i in range(colEnd, colBegin - 1, -1):
result.append(matrix[rowEnd][i])
rowEnd -= 1
if colBegin <= colEnd:
for i in range(rowEnd, rowBegin - 1, -1):
result.append(matrix[i][colBegin])
colBegin += 1
return result