054. Spiral Matrix
At a Glance
- Topic: Array
- Pattern: Analyze Pattern
- Difficulty: Medium
- LeetCode: 054
Problem Statement
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]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100Approach & Solution Steps
- Simulation with Visited Map — Use
dx, dyarrays[0, 1, 0, -1]. If you hit an edge or avisitedcell, turn 90 degrees. Time: $O(m \cdot n)$, Space: $O(m \cdot n)$ extra space for visited map. Suboptimal. - Layer-by-Layer Shrinking Boundaries — Track four integer walls. Time: $O(m \cdot n)$, Space: $O(1)$ extra space. (Always pick this)
Optimal JS Solution
function spiralOrder(matrix) {
if (matrix.length === 0) return [];
const result = [];
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
// 1. Top Row
for (let c = left; c <= right; c++) {
result.push(matrix[top][c]);
}
top++;
// 2. Right Col
for (let r = top; r <= bottom; r++) {
result.push(matrix[r][right]);
}
right--;
// Check condition before backwards sweeps
if (top <= bottom && left <= right) {
// 3. Bottom Row
for (let c = right; c >= left; c--) {
result.push(matrix[bottom][c]);
}
bottom--;
// 4. Left Col
for (let r = bottom; r >= top; r--) {
result.push(matrix[r][left]);
}
left++;
}
}
return result;
}Edge Cases & Pitfalls
- Always consider empty or null inputs.
- Watch out for off-by-one index errors.
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?