Skip to content

Commit dc394e7

Browse files
committed
solve: spiral matrix
1 parent 015843e commit dc394e7

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

spiral-matrix/evan.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
6+
if not matrix or not matrix[0]:
7+
return []
8+
9+
result = []
10+
left, right = 0, len(matrix[0]) - 1
11+
top, bottom = 0, len(matrix) - 1
12+
13+
while left <= right and top <= bottom:
14+
# Traverse from left to right
15+
for i in range(left, right + 1):
16+
result.append(matrix[top][i])
17+
# Move the top boundary down
18+
top += 1
19+
20+
# Traverse from top to bottom
21+
for i in range(top, bottom + 1):
22+
result.append(matrix[i][right])
23+
# Move the right boundary to the left
24+
right -= 1
25+
26+
if top <= bottom:
27+
# Traverse from right to left
28+
for i in range(right, left - 1, -1):
29+
result.append(matrix[bottom][i])
30+
# Move the bottom boundary up
31+
bottom -= 1
32+
33+
if left <= right:
34+
# Traverse from bottom to top
35+
for i in range(bottom, top - 1, -1):
36+
result.append(matrix[i][left])
37+
# Move the left boundary to the right
38+
left += 1
39+
40+
return result

0 commit comments

Comments
 (0)