Spiral traversal
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Spiral traversal visits a grid ring by ring: along the top, down the right, back along the bottom, up the left, and then repeat on the smaller inner ring. It is how you read or draw a table in a circular order, and a good practice for managing four shrinking edges.
Practical use cases
- Web app: Seat map or tile gallery reveal. A gallery page reveals photo tiles in a spiral from the outside to the middle as a loading animation. The script lists tile positions in spiral order, then plays them one by one. Walking the four edges and shrinking them each round gives that order without any special case for each grid size.
- Web app: Puzzle and game boards. A browser puzzle game fills or reads a grid in a spiral, as in a word-search or a maze generator. The code keeps four boundaries, top, bottom, left and right, and moves them inward after each side. It works for any rectangular grid, even a single row.
- System: Robot vacuum coverage. A robot cleaner that covers a rectangular room can follow the walls first, then circle inward. Printing and plotting machines use similar paths so every cell is visited exactly once. The ring-by-ring path avoids crossing the same floor twice, which saves battery and makes the whole job finish sooner.
The story: The Jalebi Tray Spiral
Mira's uncle brought a big tray of jalebis. They were arranged in a neat grid: 3 rows, 4 columns, numbered 1 to 12. "Eat them the way a jalebi is made," he said, "in a spiral, outside first."
Kabir said, "Easy, row by row!" That is a plain traversal, but not a spiral. Mira started at the top-left and ate right along the top row. Then down the right column, then left along the bottom row, then up the left column. The outer ring was gone.
Now the tray was smaller. The top wall had come down one step, the right wall moved left, the bottom wall moved up, the left wall moved in. She repeated the same four moves on the smaller tray, again and again, till nothing was left.
That is spiral traversal: keep four walls (top, bottom, left, right), walk one side, and pull that wall inward. A small but important check: when the tray gets thin (one row or column left), you must not walk the same sweets twice.
How to spot this problem, and where you need it
You must read, print or fill a 2D grid in a circular order from the outside inward, and the code is getting full of special cases and off-by-one mistakes.
Signs you need it
- The problem says spiral order, clockwise from the outer edge, or print the matrix in a snake or circle shape.
- The grid is not always square, and your solution breaks on a single row, single column or when the middle is reached.
- You find yourself visiting some cells twice or skipping the centre cell.
Where to use it in a project
- Animations and loading effects that reveal grid tiles, seat maps or heat maps in a pattern.
- Game boards, coverage paths for robots and printing or plotting code that must pass over each cell once.
The solution
Keep four numbers: the top row, bottom row, left column and right column of the part not yet visited. Walk the top row from left to right, then move top down by one. Walk the right column downward, then move right inward. Walk the bottom row backwards and the left column upward, shrinking each. Stop as soon as the top passes the bottom or left passes right. Check before the last two sides.
Payoff: Before: special cases for every grid shape. After: one tidy loop with four boundaries that visits every cell exactly once.
Explain it like I am 8
Walk around the edge of a room along the walls, then step in one tile and walk around the smaller ring again. Keep going in smaller and smaller rings until you reach the middle.
How it works, step by step
- Keep four walls:
top = 0,bottom = rows - 1,left = 0,right = cols - 1. - Walk the top row from left to right, then do
top++. - Walk the right column from top to bottom, then do
right--. - If rows remain, walk the bottom row right to left, then
bottom--. If columns remain, walk the left column bottom to top, thenleft++. - Repeat while
top <= bottomandleft <= right.
The code in four languages
PHP
<?php
// Read a matrix in spiral order using four shrinking walls
function spiral(array $m): array {
$out = [];
$top = 0; $bottom = count($m) - 1;
$left = 0; $right = count($m[0]) - 1;
while ($top <= $bottom && $left <= $right) {
for ($c = $left; $c <= $right; $c++) $out[] = $m[$top][$c]; // left to right
$top++;
for ($r = $top; $r <= $bottom; $r++) $out[] = $m[$r][$right]; // top to bottom
$right--;
if ($top <= $bottom) {
for ($c = $right; $c >= $left; $c--) $out[] = $m[$bottom][$c]; // right to left
$bottom--;
}
if ($left <= $right) {
for ($r = $bottom; $r >= $top; $r--) $out[] = $m[$r][$left]; // bottom to top
$left++;
}
}
return $out;
}
echo implode(', ', spiral([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])) . PHP_EOL;
// 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7JavaScript
// Read a matrix in spiral order using four shrinking walls
function spiral(m) {
const out = [];
let top = 0, bottom = m.length - 1;
let left = 0, right = m[0].length - 1;
while (top <= bottom && left <= right) {
for (let c = left; c <= right; c++) out.push(m[top][c]); // left to right
top++;
for (let r = top; r <= bottom; r++) out.push(m[r][right]); // top to bottom
right--;
if (top <= bottom) {
for (let c = right; c >= left; c--) out.push(m[bottom][c]); // right to left
bottom--;
}
if (left <= right) {
for (let r = bottom; r >= top; r--) out.push(m[r][left]); // bottom to top
left++;
}
}
return out;
}
console.log(spiral([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]).join(', '));
// 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7Java
import java.util.*;
public class Main {
// Read a matrix in spiral order using four shrinking walls
static List<Integer> spiral(int[][] m) {
List<Integer> out = new ArrayList<>();
int top = 0, bottom = m.length - 1;
int left = 0, right = m[0].length - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) out.add(m[top][c]); // left to right
top++;
for (int r = top; r <= bottom; r++) out.add(m[r][right]); // top to bottom
right--;
if (top <= bottom) {
for (int c = right; c >= left; c--) out.add(m[bottom][c]); // right to left
bottom--;
}
if (left <= right) {
for (int r = bottom; r >= top; r--) out.add(m[r][left]); // bottom to top
left++;
}
}
return out;
}
public static void main(String[] args) {
int[][] grid = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
System.out.println(spiral(grid));
// [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
}
}Go
package main
import "fmt"
// spiral reads a matrix in spiral order using four shrinking walls.
func spiral(m [][]int) []int {
var out []int
top, bottom := 0, len(m)-1
left, right := 0, len(m[0])-1
for top <= bottom && left <= right {
for c := left; c <= right; c++ { // left to right
out = append(out, m[top][c])
}
top++
for r := top; r <= bottom; r++ { // top to bottom
out = append(out, m[r][right])
}
right--
if top <= bottom {
for c := right; c >= left; c-- { // right to left
out = append(out, m[bottom][c])
}
bottom--
}
if left <= right {
for r := bottom; r >= top; r-- { // bottom to top
out = append(out, m[r][left])
}
left++
}
}
return out
}
func main() {
grid := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}
fmt.Println(spiral(grid))
// [1 2 3 4 8 12 11 10 9 5 6 7]
}Time: O(rows × cols) · Extra space: O(1) extra (besides the output). Every cell is visited exactly once, and only four wall variables are kept.
Watch out for
- Missing the two
ifchecks before the bottom and left walks. For a single row or column you will visit cells twice. - Forgetting to move a wall inward after finishing its side.
- Using the wrong direction in the bottom walk (right to left) or the left walk (bottom to top).
Quick check
- After walking the top row, which wall moves?
- top moves down (top++)
- left moves right
- bottom moves up
- Why check <code>top <= bottom</code> before walking the bottom row?
- To go faster
- To avoid reading the same row twice when only one row is left
- It is not needed
- How many times is each cell visited?
- Exactly once
- Twice
- It depends on the size