Description
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]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
Solution
Classical list problem, take care of all the boundaries! Remember to change directions and shrink the boundaries.
Time complexity:
o
(
m
∗
n
)
o(m * n)
o(m∗n)
Space complexity:
o
(
m
∗
n
)
o(m * n)
o(m∗n)
Code
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
row_l, row_h = 0, len(matrix) - 1
col_l, col_h = 0, len(matrix[0]) - 1
d = 'r'
res = []
x, y = 0, 0
while len(res) < len(matrix) * len(matrix[0]):
res.append(matrix[x][y])
if d == 'r' and y == col_h:
d = 'd'
row_l += 1
elif d == 'd' and x == row_h:
d = 'l'
col_h -= 1
elif d == 'l' and y == col_l:
d = 'u'
row_h -= 1
elif d == 'u' and x == row_l:
d = 'r'
col_l += 1
if d == 'r':
y += 1
elif d == 'd':
x += 1
elif d == 'l':
y -= 1
elif d == 'u':
x -= 1
return res