Graph traversal
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Graph traversal means visiting everything reachable from a starting point by following connections, one neighbour at a time, while remembering what you have seen. It powers anything about networks, maps and "what is connected to what".
Practical use cases
- Web app: Paint bucket in an image editor. A web-based drawing tool fills a clicked area with a colour. Starting at the clicked pixel, it spreads to touching pixels of the same colour and stops at edges, filling exactly the right region. Clicking the sky turns the whole sky blue and nothing else, in a fraction of a second.
- Web app: Friends of friends on a social site. A social app suggests people you may know. Visiting your friends, then their friends, gives people two connections away, and stops after that level. Users see a "people you may know" list built from their friends' friends, without scanning every account.
- Web app: Web crawler or sitemap checker. An SEO tool starts at the home page, follows every link to other pages, and remembers visited pages so it does not loop forever, to find broken links across the whole site. The crawler reports broken links across a 5,000-page site and never gets stuck in a loop.
- System: Maps and games. Counting islands on a map, finding connected regions, or exploring a game level all work by spreading outward from a start cell. Each cell is visited once, so even big maps and levels are explored quickly.
The story: Islands on the Map
Kabir’s geography homework came with a satellite photo of a lake, turned into a grid of squares: 1 for land and 0 for water. "How many islands are in this lake?" it asked. Kabir counted the 1s: nine. Wrong! Several 1s sat side by side and formed a single island.
Mira found the idea: "An island is a bunch of land squares that touch each other. So: scan the map. When you meet a land square you haven’t seen yet, that is a new island. Then walk across it (up, down, left, right) and mark every square you pass as visited, so you never count it twice."
Walking across everything that is connected is graph traversal. Each square is a node; touching squares are connected by an edge. You can walk using a stack or recursion (DFS, go deep first) or a queue (BFS, ring by ring). Both reach exactly the same connected group.
The smell: "islands", "connected", "reachable", "regions", "flood fill", "friends of friends", "can I get from A to B". Whenever things are linked and the question is about what you can reach, traverse and keep a visited set so you never loop forever.
How to spot this problem, and where you need it
Your data is things connected to other things (pixels, users, pages, rooms), and you need to know what is reachable, how many separate groups exist, or how far apart things are.
Signs you need it
- The data is a grid, a set of links, or pairs like "A is connected to B".
- Questions: "is X reachable from Y", "how many groups or islands", "shortest number of hops", "find all connected items".
- A plain loop over a list cannot work because every item leads to others you have not visited yet.
Where to use it in a project
- Flood fill and region selection in image editors, maps and games.
- Social, referral and recommendation features based on who is connected to whom.
- Crawlers and link checkers that follow links and must remember which pages were already seen.
The solution
Keep a "visited" list and a to-do list. Put the start in the to-do list. Repeatedly take an item, mark it visited, and add each of its unvisited neighbours. Using a queue (breadth-first) explores level by level and finds fewest hops; using a stack or recursion (depth-first) dives deep first. To count groups, start a new traversal from every unvisited item and count the starts.
Payoff: Before: a flood fill that revisits pixels endlessly or misses regions. After: every pixel visited exactly once.
Explain it like I am 8
You spill paint on one square of a chessboard and it spreads to every touching square of the same colour, then stops at the edges. That spreading is traversal. Counting islands is counting how many times you had to start a new paint spill.
How it works, step by step
- Spot the clue: a grid, a network, or relationships where "connected" or "reachable" matters.
- Name the nodes and neighbours: in a grid, neighbours are the 4 cells up, down, left, right (stay inside the border!).
- Keep a visited marker (a set, or overwrite the cell) so no place is processed twice.
- Scan everything. At each unvisited land cell, count one more island and traverse from it with a stack (DFS) or queue (BFS), marking all reachable land.
- Same recipe, different questions: shortest steps (BFS), is there a path, size of the biggest region, number of groups.
The code in four languages
PHP
<?php
// Classic: "Number of Islands": traverse each island once with a stack (DFS).
function countIslands(array $grid): int {
$rows = count($grid);
$cols = count($grid[0]);
$count = 0;
for ($r = 0; $r < $rows; $r++) {
for ($c = 0; $c < $cols; $c++) {
if ($grid[$r][$c] !== 1) continue; // water or already visited
$count++; // an unseen land cell: a new island
$grid[$r][$c] = 0; // mark visited (we work on a copy)
$stack = [[$r, $c]];
while ($stack) {
[$y, $x] = array_pop($stack);
foreach ([[1, 0], [-1, 0], [0, 1], [0, -1]] as [$dy, $dx]) {
$ny = $y + $dy;
$nx = $x + $dx;
if ($ny >= 0 && $ny < $rows && $nx >= 0 && $nx < $cols && $grid[$ny][$nx] === 1) {
$grid[$ny][$nx] = 0; // mark when pushed, so it is added only once
$stack[] = [$ny, $nx];
}
}
}
}
}
return $count;
}
$map = [[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]];
echo countIslands($map); // 3JavaScript
// Classic: "Number of Islands": traverse each island once with a stack (DFS).
function countIslands(input) {
const grid = input.map((row) => [...row]); // work on a copy
const rows = grid.length, cols = grid[0].length;
let count = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] !== 1) continue; // water or already visited
count++; // an unseen land cell: a new island
grid[r][c] = 0; // mark visited
const stack = [[r, c]];
while (stack.length) {
const [y, x] = stack.pop();
for (const [dy, dx] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
const ny = y + dy, nx = x + dx;
if (ny >= 0 && ny < rows && nx >= 0 && nx < cols && grid[ny][nx] === 1) {
grid[ny][nx] = 0; // mark when pushed, so it is added only once
stack.push([ny, nx]);
}
}
}
}
}
return count;
}
const map = [[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]];
console.log(countIslands(map)); // 3Java
import java.util.*;
public class Main {
// Classic: "Number of Islands": traverse each island once with a stack (DFS).
static int countIslands(int[][] input) {
int rows = input.length, cols = input[0].length;
int[][] grid = new int[rows][];
for (int r = 0; r < rows; r++) grid[r] = input[r].clone(); // work on a copy
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int count = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] != 1) continue; // water or already visited
count++; // an unseen land cell: a new island
grid[r][c] = 0; // mark visited
Deque<int[]> stack = new ArrayDeque<>();
stack.push(new int[]{r, c});
while (!stack.isEmpty()) {
int[] cell = stack.pop();
for (int[] d : dirs) {
int ny = cell[0] + d[0], nx = cell[1] + d[1];
if (ny >= 0 && ny < rows && nx >= 0 && nx < cols && grid[ny][nx] == 1) {
grid[ny][nx] = 0; // mark when pushed, so it is added only once
stack.push(new int[]{ny, nx});
}
}
}
}
}
return count;
}
public static void main(String[] args) {
int[][] map = {{1,1,0,0,0},{1,1,0,0,0},{0,0,1,0,0},{0,0,0,1,1}};
System.out.println(countIslands(map)); // 3
}
}Go
package main
import (
"fmt"
"slices"
)
// countIslands is the classic "Number of Islands": traverse each island once with a stack (DFS).
func countIslands(input [][]int) int {
grid := make([][]int, len(input))
for r, row := range input {
grid[r] = slices.Clone(row) // work on a copy
}
rows, cols := len(grid), len(grid[0])
dirs := [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
count := 0
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
if grid[r][c] != 1 {
continue // water or already visited
}
count++ // an unseen land cell: a new island
grid[r][c] = 0 // mark visited
stack := [][2]int{{r, c}}
for len(stack) > 0 {
cell := stack[len(stack)-1]
stack = stack[:len(stack)-1]
for _, d := range dirs {
ny, nx := cell[0]+d[0], cell[1]+d[1]
if ny >= 0 && ny < rows && nx >= 0 && nx < cols && grid[ny][nx] == 1 {
grid[ny][nx] = 0 // mark when pushed, so it is added only once
stack = append(stack, [2]int{ny, nx})
}
}
}
}
}
return count
}
func main() {
grid := [][]int{{1, 1, 0, 0, 0}, {1, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 1}}
fmt.Println(countIslands(grid)) // 3
}Time: O(rows × cols) · Extra space: O(rows × cols). Every cell is visited a constant number of times; the stack can hold a whole island in the worst case.
Watch out for
- Not marking cells as visited, so the walk goes back and forth forever (or counts the same island many times).
- Forgetting border checks, which reads outside the grid.
- Marking visited only when popping (not when pushing), so the same cell is pushed many times.
Quick check
- Which clue points to graph traversal?
- "count connected regions / can I reach X from Y"
- "sorted array"
- "maximum sum"
- "merge overlapping meetings"
- Why keep a visited set?
- To save memory
- To sort the nodes
- To avoid processing places twice or looping forever
- To find shortest paths
- What is the difference between DFS and BFS here?
- They find different islands
- DFS goes deep with a stack; BFS goes ring by ring with a queue
- BFS cannot count islands
- DFS needs a sorted grid