Graphs
Drop ink on any land square you have not coloured yet. It spreads to every square joined to it, but never crosses water. Each drop is one island, and counting the drops counts the islands.
2 · Watch
Graphs in 60 seconds
3 · Now you drive
Number of Islands
4 · Your turn
Start from this
// Mark on push, so no node is queued twice.
const seen = new Set([start]);
const queue = [start];
// Read with an index: shift() is O(n) in JavaScript.
for (let head = 0; head < queue.length; head++) {
// Oldest first: the closest nodes go first.
const node = queue[head];
for (const next of neighbours(node)) {
if (seen.has(next)) continue;
seen.add(next);
queue.push(next);
}
}Easy ways to go wrong
- Marking a node when you pop it instead of when you push it, so it’s queued twice.
- Forgetting the graph may have more than one connected piece.
- Using DFS for a shortest path. BFS finds it when every edge costs the same; different costs need Dijkstra.
- Counting steps per node popped instead of per layer. Finish the whole layer, then add one.
Flood fill
Start at one cell or node and spread to every neighbour you haven’t seen yet.
- Medium01
Number of Islands
The one you just watched. Write it from memory.
Each new land cell starts a flood that claims its whole group.
- Time
- O(m·n)
- Space
- O(m·n)
Also works with Advanced Graphs.
- Medium02
Clone Graph
Same flood, but copy each node as you claim it.
A map from old node to new node stops you copying anything twice.
- Time
- O(V + E)
- Space
- O(V)
- Medium03
Pacific Atlantic Water Flow
Flood from both oceans, keep the overlap.
Work backwards: flood uphill from each sea and keep the overlap.
- Time
- O(m·n)
- Space
- O(m·n)
Topological order
Take whatever has nothing left to wait for. If some never free up, there’s a loop.
- Medium04
Course Schedule
Take what has nothing left to wait for. If some never free up, there’s a loop.
Tasks and rules form arrows. A loop makes it impossible.
- Time
- O(V + E)
- Space
- O(V + E)
Also works with Advanced Graphs.
- Medium05
Course Schedule II
Same queue as Course Schedule. The order you take courses in is the answer.
Take whatever waits for nothing, then free up what came after it. The queue fills in a valid order.
- Time
- O(V + E)
- Space
- O(V + E)
Also works with Advanced Graphs.
O(V + E) time · O(V + E) spacefunction findOrder(numCourses: number, prerequisites: number[][]): number[] { const next: number[][] = Array.from({ length: numCourses }, () => []); const needs = new Array(numCourses).fill(0); // how many courses each one still waits for for (const [course, before] of prerequisites) { next[before].push(course); needs[course]++; } // Start with every course that waits for nothing. The queue is also the answer. const order: number[] = []; for (let c = 0; c < numCourses; c++) if (needs[c] === 0) order.push(c); for (let head = 0; head < order.length; head++) { for (const after of next[order[head]]) { needs[after]--; if (needs[after] === 0) order.push(after); } } // A loop keeps some courses waiting forever. return order.length === numCourses ? order : []; }
Fewest steps with BFS
BFS moves out one layer at a time, so the first time it reaches something is the shortest way.
- Medium06
Rotting Oranges
Put every rotten orange in the queue first. Each BFS layer is one minute.
Many starting points spread at the same speed, so start them all together and count the layers.
- Time
- O(m·n)
- Space
- O(m·n)
O(m·n) time · O(m·n) spacefunction orangesRotting(grid: number[][]): number { // Every rotten orange starts in the queue, so they all spread at once. const queue: [number, number][] = []; let fresh = 0; for (let r = 0; r < grid.length; r++) { for (let c = 0; c < grid[0].length; c++) { if (grid[r][c] === 2) queue.push([r, c]); else if (grid[r][c] === 1) fresh++; } } let minutes = 0; let head = 0; while (fresh > 0 && head < queue.length) { // Everything in the queue now rots its neighbours this minute. const end = queue.length; for (; head < end; head++) { const [r, c] = queue[head]; for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { const nr = r + dr, nc = c + dc; if (grid[nr]?.[nc] !== 1) continue; grid[nr][nc] = 2; fresh--; queue.push([nr, nc]); } } minutes++; } // Fresh oranges left over were never next to anything rotten. return fresh === 0 ? minutes : -1; } - Hard07
Word Ladder
Words are nodes, and one-letter changes are the links. BFS finds the fewest.
Fewest moves, every move costs the same: that’s BFS. Group words under patterns like h*t to find neighbours fast.
- Time
- O(n·L²)
- Space
- O(n·L²)
O(n·L²) time · O(n·L²) spacefunction ladderLength(beginWord: string, endWord: string, wordList: string[]): number { // Group words by pattern: "hot" sits under "*ot", "h*t" and "ho*". const groups = new Map<string, string[]>(); for (const word of wordList) { for (let i = 0; i < word.length; i++) { const key = word.slice(0, i) + "*" + word.slice(i + 1); const group = groups.get(key); if (group) group.push(word); else groups.set(key, [word]); } } const seen = new Set([beginWord]); let layer = [beginWord]; // Each layer is one more word in the sequence. for (let length = 1; layer.length > 0; length++) { const nextLayer: string[] = []; for (const word of layer) { if (word === endWord) return length; for (let i = 0; i < word.length; i++) { const key = word.slice(0, i) + "*" + word.slice(i + 1); for (const next of groups.get(key) ?? []) { if (seen.has(next)) continue; seen.add(next); nextLayer.push(next); } // Everyone in this group is queued now, so it never needs reading again. groups.delete(key); } } layer = nextLayer; } return 0; } - Hard08
Bus Routes
Search over buses, not stops. Each bus you board is one more layer.
You count rides, not stops, so the buses are the nodes. Two buses link when they share a stop.
- Time
- O(s)
- Space
- O(s)
O(s) time · O(s) spacefunction numBusesToDestination(routes: number[][], source: number, target: number): number { if (source === target) return 0; // Which buses call at each stop. const buses = new Map<number, number[]>(); routes.forEach((route, bus) => { for (const stop of route) { const list = buses.get(stop); if (list) list.push(bus); else buses.set(stop, [bus]); } }); const rode = new Array(routes.length).fill(false); // A layer holds the buses you can be on after that many rides. let layer = buses.get(source) ?? []; for (const bus of layer) rode[bus] = true; for (let rides = 1; layer.length > 0; rides++) { const nextLayer: number[] = []; for (const bus of layer) { for (const stop of routes[bus]) { if (stop === target) return rides; for (const other of buses.get(stop) ?? []) { if (rode[other]) continue; rode[other] = true; nextLayer.push(other); } // Every bus at this stop is boarded now, so skip the stop next time. buses.delete(stop); } } layer = nextLayer; } return -1; }