Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Spiral Matrix

LeetCode #54Medium
Four shrinking boundaries

Given an m x n matrix, return all of its elements in spiral order, traversing the outer ring clockwise and spiraling inward.

Asked atAmazonMicrosoftGoogle
step 1 / 21
3 × 4 grid
1
2
3
4
5
6
7
8
9
10
11
12
spiral order
Boundary simulation
1top=0, bottom=R−1, left=0, right=C−1
2while top ≤ bottom and left ≤ right:
3
4 for c in left..right: take (top, c)
5 top++
6 for r in top..bottom: take (r, right)
7 right−−
8 if top ≤ bottom:
9 for c in right..left: take (bottom, c)
10 bottom−−
11 if left ≤ right:
12 for r in bottom..top: take (r, left)
13 left++
14return collected
state
  • rows3
  • cols4

line 1Read the grid in a SPIRAL: across the top, down the right, back along the bottom, up the left, then inward and repeat. The clean way is four boundaries — top, bottom, left, right — that close in after each edge is consumed.