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
Given an m x n
matrix, return all elements of the matrix in spiral order.
This solution simulates the spiral traversal using four directions (right, down, left, up). A boolean matrix vis
tracks visited cells.
Algorithm:
i
, j
, k
(direction), ans
(result list), and vis
(visited matrix).m * n
times:
matrix[i][j]
to ans
.matrix[i][j]
as visited.k
).k = (k + 1) % 4
).i
and j
based on the new direction.Time Complexity: O(mn) - We visit each cell once.
Space Complexity: O(mn) - For the vis
matrix and ans
list.
This solution optimizes space by modifying the matrix itself to track visited cells. We add a large constant (300) to a cell after visiting it. This works because the problem states that matrix elements are in the range [-100, 100].
Algorithm:
i
, j
, k
, ans
.m * n
times:
matrix[i][j]
to ans
.matrix[i][j]
to mark it as visited.k
).i
and j
.Time Complexity: O(m*n) - We visit each cell twice (once for traversal, once for restoration). Space Complexity: O(1) - We use constant extra space. The matrix itself is modified but restored.
Code (Python3 - Solution 1):
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
dirs = (0, 1, 0, -1, 0) # Right, Down, Left, Up
vis = [[False] * n for _ in range(m)]
i = j = k = 0
ans = []
for _ in range(m * n):
ans.append(matrix[i][j])
vis[i][j] = True
x, y = i + dirs[k], j + dirs[k + 1]
if x < 0 or x >= m or y < 0 or y >= n or vis[x][y]:
k = (k + 1) % 4
i += dirs[k]
j += dirs[k + 1]
return ans
Code (Python3 - Solution 2):
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
dirs = (0, 1, 0, -1, 0)
i = j = k = 0
ans = []
for _ in range(m * n):
ans.append(matrix[i][j])
matrix[i][j] += 300
x, y = i + dirs[k], j + dirs[k + 1]
if x < 0 or x >= m or y < 0 or y >= n or matrix[x][y] > 100:
k = (k + 1) % 4
i += dirs[k]
j += dirs[k + 1]
for i in range(m):
for j in range(n):
matrix[i][j] -= 300
return ans
(Other language implementations would follow a similar structure, adapting syntax and data structures as needed. The core logic remains the same.)