Spiral Matrix
Difficulty: Medium
Given a grid with m rows and n columns, return every number in spiral order. Start at the top-left corner, go right along the top, down the right side, left along the bottom, up the left side, then move inward to the next ring until every cell is visited.
Examples
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Across the top (1,2,3), down the right side (6,9), across the bottom right-to-left (8,7), up the left side (4), then the single cell left in the middle (5).
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]
Input: matrix = [[1]]
Output: [1]
Constraints
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
Approach
The direct way walks one cell at a time in the current direction (right, down, left or up). When the next step would leave the grid or hit a visited cell, turn 90 degrees. This is how you'd trace it by hand, but it needs a separate "visited" grid.
A cleaner approach tracks four shrinking boundaries: the top row, bottom row, left column and right column of the region left to visit. Sweep each edge in turn:
- Top row, left to right.
- Right column, top to bottom.
- Bottom row, right to left.
- Left column, bottom to top.
After each sweep, move that boundary inward by one. Stop when the boundaries cross. Every cell is visited once, with no "visited" grid.
Solutions
Brute Force - Simulate With a Visited Grid
Walk one step at a time, starting to the right. When the next cell is off the grid or already visited, turn 90 degrees clockwise. A same-size grid of booleans records visited cells.
function spiralOrder(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
const visited = Array.from({ length: rows }, () => new Array(cols).fill(false));
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up
const result = [];
let r = 0, c = 0, dir = 0;
for (let i = 0; i < rows * cols; i++) {
result.push(matrix[r][c]);
visited[r][c] = true;
const [dr, dc] = directions[dir];
let nr = r + dr;
let nc = c + dc;
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || visited[nr][nc]) {
dir = (dir + 1) % 4;
nr = r + directions[dir][0];
nc = c + directions[dir][1];
}
r = nr;
c = nc;
}
return result;
}Time: O(m · n) · Space: O(m · n), for the visited grid
Optimal - Four Shrinking Boundaries
Track the top, bottom, left and right edges of the unvisited region. Sweep the top row, right column, bottom row, then left column, shrinking each boundary right after its sweep. Stop when the boundaries cross.
function spiralOrder(matrix) {
const result = [];
let top = 0, bottom = matrix.length - 1;
let left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let c = left; c <= right; c++) result.push(matrix[top][c]);
top++;
for (let r = top; r <= bottom; r++) result.push(matrix[r][right]);
right--;
if (top <= bottom) {
for (let c = right; c >= left; c--) result.push(matrix[bottom][c]);
bottom--;
}
if (left <= right) {
for (let r = bottom; r >= top; r--) result.push(matrix[r][left]);
left++;
}
}
return result;
}Time: O(m · n) · Space: O(1) extra space, beyond the output list