54. Spiral Matrix — Step-by-Step Visualization
mediumLeetCode #54ArrayMatrixSimulation
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]`
Algorithm Pattern
Boundary Contraction
Key Idea
Maintain four pointers representing the current boundaries: `top`, `bottom`, `left`, and `right`. Move in four directions (right, down, left, up) sequentially, shrinking the corresponding boundary after each pass. Terminate when boundaries overlap.
Step-by-Step Approach
- Initialize `top = 0`, `bottom = m-1`, `left = 0`, `right = n-1`.
- While `left <= right` and `top <= bottom`:
- 1. Move right: Traverse from `left` to `right` at row `top`. Increment `top`.
- 2. Move down: Traverse from `top` to `bottom` at column `right`. Decrement `right`.
- 3. Move left (if `top <= bottom`): Traverse from `right` to `left` at row `bottom`. Decrement `bottom`.
- 4. Move up (if `left <= right`): Traverse from `bottom` to `top` at column `left`. Increment `left`.
- Repeat until all elements are visited.
Common Gotchas
- Crucial: Check `top <= bottom` and `left <= right` before the 'left' and 'up' moves to prevent double-visiting rows/columns in non-square matrices.