Date and Time: Jul 14, 2024, 12:55 (EST)
Link: https://leetcode.com/problems/spiral-matrix/
Given an m x n
matrix
, return all elements of the matrix
in spiral order.
Example 1:
Input: matrix = [ [1,2,3], [4,5,6], [7,8,9] ]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
-
m == matrix.length
-
n == matrix[i].length
-
1 <= m, n <= 10
-
-100 <= matrix[i][j] <= 100
We just repeat four directions moving: left -> right, top -> bottom, right -> left, bottom -> top
. So we use four pointers l, r, t, b
to indicate these four boundaries. And after each time we finish a traversing, we just shrink the boundary until l == r or t == b
, then we can break
to return res
.
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
# l -> r, t -> b, r -> l, b -> t
l, r = 0, len(matrix[0])
t, b = 0, len(matrix)
res = []
while l < r and t < b:
# left -> right
for i in range(l, r):
res.append(matrix[t][i])
t += 1 # Top is done
# top -> bottom
for i in range(t, b):
res.append(matrix[i][r-1])
r -= 1 # Right-most column done
if l == r or t == b:
break
# right -> left
for i in range(r - 1, l - 1, -1):
res.append(matrix[b - 1][i])
b -= 1 # Bottom done
# bottom -> top
for i in range(b - 1, t - 1, -1):
res.append(matrix[i][l])
l += 1 # left-most column done
return res
Time Complexity:
Space Complexity: