top
First unvisited row. Swept left → right.
always executed
A weather-monitoring station deploys sensors across an m × n grid. To run diagnostics,
the system spirals inward from the perimeter — pinging each sensor exactly once.
Four boundary pointers — top, right, bottom,
and left — define the rectangle. Walk its perimeter, shrink inward, repeat.
At any moment during the spiral walk, four integers mark the edges of the unvisited region. Each boundary maps to a sweep direction and a distinctive line style used throughout this page.
First unvisited row. Swept left → right.
always executedLast unvisited column. Swept top+1 → bottom.
always executedLast unvisited row. Swept right−1 → left.
if (top < bottom)First unvisited column. Swept bottom−1 → top+1.
if (left < right)
The outer condition while (top ≤ bottom && left ≤ right)
ensures we stop once the rectangle has fully collapsed.
Traverse columns left through right at row top.
Traverse rows top + 1 through bottom at column right.
Traverse columns right − 1 down to left at row bottom. The guard prevents re-walking a single remaining row.
Traverse rows bottom − 1 down to top + 1 at column left. The guard prevents re-walking a single remaining column.
top++ bottom-- left++ right--
Without the two guard conditions, the algorithm would revisit cells whenever the remaining rectangle collapses to a single row or a single column.
After shrinking, if top equals bottom, only a single
row survives. The top sweep already visits every cell in that row from left to
right. Without the guard top < bottom, the bottom sweep would
traverse the same row in reverse — duplicating every value.
Try the 3 × 4 preset to see this guard activate on layer 1.
After shrinking, if left equals right, only a single
column survives. The right sweep already visits every cell in that column from
top to bottom. Without the guard left < right, the left sweep
would traverse the same column in reverse — duplicating every value.
Try the 5 × 3 preset to see this guard activate on layer 1.