Algorithm-Day19-Spiral-Matrix-lc-54
🧩 Problem 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]] |
💡 Approach: Layer-by-Layer Traversal
✨ Key Idea
We maintain four boundaries:
top
,bottom
,left
,right
At each step:
- Traverse from
left
toright
alongtop
. - Traverse from
top + 1
tobottom
alongright
. - Traverse from
right - 1
toleft
alongbottom
(only iftop < bottom
). - Traverse from
bottom - 1
totop + 1
alongleft
(only ifleft < right
).
After each step, we shrink the boundaries inward.
🔢 Java Code
1 | import java.util.*; |
⏱ Time and Space Complexity
- Time Complexity: O(m × n)
Each cell is visited exactly once. - Space Complexity: O(1) extra space
(excluding output list)
✍️ Summary
- Boundary shrinking is a classic matrix traversal technique.
- Spiral order appears in related problems like
Spiral Matrix II
(filling numbers),lc-59
. - Make sure to check conditions carefully when shrinking boundaries to avoid duplicates.
Matrix traversal patterns (row-wise, column-wise, spiral, zigzag) are common interview topics — good to master!