[Medium] 54. Spiral Matrix
Given an m x n matrix, return all elements of the matrix in spiral order.
Examples
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
Thinking Process
There are two main approaches to solve this problem:
- Boundary Tracking: Use four boundaries (top, bottom, left, right) and traverse in spiral order
- Direction Simulation: Use direction vectors and mark visited cells to simulate spiral movement
Common Approaches
Typical techniques for this pattern:
| Approach | Time | Space | Notes |
|---|---|---|---|
| Row/column traversal | O(nm) | O(1) | Simulation, spiral |
| BFS/DFS on grid | O(nm) | O(nm) | Islands, shortest path |
| Matrix as graph (this problem) | O(nm) | O(nm) | 4/8-directional neighbors |
| Transpose / rotate | O(nm) | O(1) | In-place rotation tricks |
Solution
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> rtn;
const int rows = matrix.size(), cols = matrix[0].size();
int up = 0, left = 0, right = cols - 1, down = rows - 1;
while(rtn.size() < rows * cols) {
// Traverse right along top row
for(int col = left; col <= right; col++) {
rtn.push_back(matrix[up][col]);
}
// Traverse down along right column
for(int row = up + 1; row <= down; row++) {
rtn.push_back(matrix[row][right]);
}
// Traverse left along bottom row (if not same as top)
if(up != down) {
for (int col = right - 1; col >= left; col--) {
rtn.push_back(matrix[down][col]);
}
}
// Traverse up along left column (if not same as right)
if(left != right) {
for(int row = down - 1; row > up; row--) {
rtn.push_back(matrix[row][left]);
}
}
// Move boundaries inward
left++;
right--;
up++;
down--;
}
return rtn;
}
};
Solution Explanation
Approach: Matrix as graph (this problem)
Key idea: There are two main approaches to solve this problem:
How the code works:
- Boundary Tracking: Use four boundaries (top, bottom, left, right) and traverse in spiral order
- Direction Simulation: Use direction vectors and mark visited cells to simulate spiral movement
Walkthrough — input matrix = [[1,2,3],[4,5,6],[7,8,9]], expected output [1,2,3,6,9,8,7,4,5]:
- Initialize variables from the problem setup.
- Apply the main loop / recursion until the condition is met.
- Confirm the result matches the expected output.
Common Mistakes
- Off-by-one errors in boundary conditions
- Not handling single row/column cases properly
- Incorrect boundary updates after each spiral
- Missing edge cases for 1x1 matrices
Related Problems
References
- LC 54: Spiral Matrix on LeetCode
- LeetCode Discuss — LC 54: Spiral Matrix
- LeetCode Editorial (may require premium)
Key Takeaways
- Boundary Management: Track four boundaries and move them inward after each complete spiral
- Edge Cases: Handle single row/column matrices with conditional checks
- Direction Changes: Use direction vectors to simulate spiral movement
- Visited Marking: Mark cells as visited to avoid revisiting them