File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments