Spiral Matrix · Optimal Solution

The shrinking rectangle, made visible.

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.


Interactive

Watch the algorithm run


Concept

Four boundaries define the rectangle

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.

top

First unvisited row. Swept left → right.

always executed

right

Last unvisited column. Swept top+1 → bottom.

always executed

bottom

Last unvisited row. Swept right−1 → left.

if (top < bottom)

left

First unvisited column. Swept bottom−1 → top+1.

if (left < right)

Algorithm

One iteration of the loop

The outer condition while (top ≤ bottom && left ≤ right) ensures we stop once the rectangle has fully collapsed.

  1. 1

    Walk top row

    Traverse columns left through right at row top.

  2. 2

    Walk right column

    Traverse rows top + 1 through bottom at column right.

  3. 3
    if (top < bottom)

    Walk bottom row

    Traverse columns right − 1 down to left at row bottom. The guard prevents re-walking a single remaining row.

  4. 4
    if (left < right)

    Walk left column

    Traverse rows bottom − 1 down to top + 1 at column left. The guard prevents re-walking a single remaining column.

  5. 5

    Shrink all boundaries

    top++ bottom-- left++ right--

Edge Cases

Why the guards exist

Without the two guard conditions, the algorithm would revisit cells whenever the remaining rectangle collapses to a single row or a single column.

When one row remains

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.

top
6 7
bottom skipped

Try the 3 × 4 preset to see this guard activate on layer 1.

When one column remains

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.

right
5 8 11
left skipped

Try the 5 × 3 preset to see this guard activate on layer 1.