1- # Approach: Set Up Boundaries
1+ # Approach 1 : Set Up Boundaries
22
3- # Time: O(m * n), m = number of rows, n = number of columns
3+ # Time: O(m * n)
44# Space: O(1)
55
66class Solution :
77 def spiralOrder (self , matrix : List [List [int ]]) -> List [int ]:
88 result = []
9- rows , columns = len (matrix ), len (matrix [0 ])
10- up = 0
11- left = 0
12- right = columns - 1
9+ rows , cols = len (matrix ), len (matrix [0 ])
10+ up = left = 0
11+ right = cols - 1
1312 down = rows - 1
1413
15- while len (result ) < rows * columns :
16- # Left to Right
14+ while len (result ) < rows * cols :
15+ # Traverse left to right
1716 for col in range (left , right + 1 ):
1817 result .append (matrix [up ][col ])
1918
20- # Downwards
19+ # Traverse downwards
2120 for row in range (up + 1 , down + 1 ):
2221 result .append (matrix [row ][right ])
2322
23+ # Make sure we are on a different row
2424 if up != down :
25- # Right to Left
25+ # Traverse right to left
2626 for col in range (right - 1 , left - 1 , - 1 ):
2727 result .append (matrix [down ][col ])
2828
29+ # Make sure we are on a different col
2930 if left != right :
30- # Upwards
31+ # Traverse upwards
3132 for row in range (down - 1 , up , - 1 ):
3233 result .append (matrix [row ][left ])
3334
@@ -37,3 +38,5 @@ def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
3738 down -= 1
3839
3940 return result
41+
42+
0 commit comments