Spiral Matrix
Spiral Matrix
2D MatrixSimulation
Problem Statement
Given an m x n matrix, return all elements of the matrix in spiral order.
Example
Example 1:
1
2
3
4
5
6
7
8
9
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Solution
The problem can be solved by simulating the spiral traversal. We can use four pointers to define the boundaries of the current layer of the matrix: `rowStart`, `rowEnd`, `colStart`, and `colEnd`.
We traverse the matrix layer by layer, from the outside towards the center. In each layer, we traverse right, then down, then left, and finally up, adding the elements to our result list and shrinking the boundaries after each traversal.
Algorithm Steps
- Initialize four boundary pointers: `rowStart`, `rowEnd`, `colStart`, `colEnd`.
- While `rowStart <= rowEnd` and `colStart <= colEnd`:
- Traverse right across the top row (`rowStart`). After, increment `rowStart`.
- Traverse down the rightmost column (`colEnd`). After, decrement `colEnd`.
- If boundaries are still valid, traverse left across the bottom row (`rowEnd`). After, decrement `rowEnd`.
- If boundaries are still valid, traverse up the leftmost column (`colStart`). After, increment `colStart`.
- Repeat until the boundaries cross.
Spiral Matrix Traversal
Progress1 / 1
Ready to start.
1
2
3
4
5
6
7
8
9
10
11
12
Result: []
Spiral Matrix