54. Spiral Matrix
Given an m x n matrix, return all elements of the matrix in spiral order
ArrayExample 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.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100
Approach
Solution
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
# 1. Top Row
for c in range(left, right + 1):
res.append(matrix[top][c])
top += 1
# 2. Right Column
for r in range(top, bottom + 1):
res.append(matrix[r][right])
right -= 1
# 3. Bottom Row
if top <= bottom:
for c in range(right, left - 1, -1):
res.append(matrix[bottom][c])
bottom -= 1
# 4. Left Column
if left <= right:
for r in range(bottom, top - 1, -1):
res.append(matrix[r][left])
left += 1
return res