AlgoViz

Spiral Matrix

Medium

Four shrinking boundaries

In simple words

Read the grid in a spiral: right across the top, down the right, left along the bottom, up the left, then inward.

The idea

Keep top, bottom, left, right borders. Walk right along top, down the right, left along bottom, up the left — shrinking the matching border after each pass until they cross.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Step 1 of 18. Peel the matrix in rings: go right along the top, down the right, left along the bottom, up the left.

1/18
Optimal
timeO(rows·cols)spaceO(1)

Peel the matrix ring by ring.

1while (top <= bottom && left <= right) {2  for (let c=left; c<=right; c++) out.push(M[top][c]);    top++;3  for (let r=top; r<=bottom; r++) out.push(M[r][right]);  right--;4  if (top<=bottom) for (let c=right;c>=left;c--) out.push(M[bottom][c]); bottom--;5  if (left<=right) for (let r=bottom;r>=top;r--) out.push(M[r][left]);   left++;6}

Input

grid
4 × 4

Memory

at
cells marked
0

Output

output
done

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:
[1, 2, 3, 6, 9, 8, 7, 4, 5]
Explanation:
Peel the outer ring, then spiral inward.

Example 2

Input:
matrix = [[1,2],[3,4]]
Output:
[1, 2, 4, 3]
Explanation:
1,2,4,3 winds around.

Example 3

Input:
matrix = [[1]]
Output:
[1]
Explanation:
A single cell.

Finished the walkthrough? Add it to your streak.