File tree 1 file changed +52
-0
lines changed
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # 54. Spiral Matrix
3
+
4
+ to traverse the matrix in a spiral order:
5
+ 1. do boundary-tracking
6
+ 2. iterate in layers
7
+ - move right, move down, move left, move up
8
+ - shrink the boundaries
9
+ 4. return the result
10
+
11
+ # Time and Space Complexity
12
+
13
+ ```
14
+ TC: O(m * n)
15
+ SC: O(1)
16
+ ```
17
+
18
+ #### TC is O(m * n):
19
+ move through the 2D matrix just once. = O(m * n)
20
+
21
+ #### SC is O(1):
22
+ result list is excluded from auxiliary space, so it's = O(1)
23
+ '''
24
+
25
+ class Solution :
26
+ def spiralOrder (self , matrix : List [List [int ]]) -> List [int ]:
27
+ top = 0
28
+ left = 0
29
+ bottom = len (matrix ) - 1
30
+ right = len (matrix [0 ]) - 1
31
+ result = [] # SC: O(1)
32
+
33
+ while top <= bottom and left <= right :
34
+ for i in range (left , right + 1 ):
35
+ result .append (matrix [top ][i ])
36
+ top += 1
37
+
38
+ for i in range (top , bottom + 1 ):
39
+ result .append (matrix [i ][right ])
40
+ right -= 1
41
+
42
+ if top <= bottom :
43
+ for i in range (right , left - 1 , - 1 ):
44
+ result .append (matrix [bottom ][i ])
45
+ bottom -= 1
46
+
47
+ if left <= right :
48
+ for i in range (bottom , top - 1 , - 1 ):
49
+ result .append (matrix [i ][left ])
50
+ left += 1
51
+
52
+ return result
You can’t perform that action at this time.
0 commit comments