54. Spiral Matrix ๐
Last updated
Last updated
Difficulty: Medium
- Tags: Matrix
, Simulation
Given an m x n
matrix, return all elements of the matrix in spiral order.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
To traverse the matrix in spiral order, we use boundary pointers for rows and columns and move in the order: left-to-right, top-to-bottom, right-to-left, and bottom-to-top.
Initialization:
Define four boundary variables: top
, bottom
, left
, and right
.
Traversal:
Left to Right: Traverse the current top row and increment top
.
Top to Bottom: Traverse the current right column and decrement right
.
Right to Left: Traverse the current bottom row (if valid) and decrement bottom
.
Bottom to Top: Traverse the current left column (if valid) and increment left
.
Result:
Stop traversal when top > bottom
or left > right
.
O(m * n):
Each element of the matrix is visited exactly once.
O(1):
No additional space is used apart from the result list (output space not counted).
You can find the full solution here.