← All lessons
How graph search works
Same graph, queue or stack
bfs.js
function bfs(graph, start) { const queue = [start]; const seen = new Set([start]); // read from the front with an index: O(1), unlike shift() for (let head = 0; head < queue.length; head++) { const node = queue[head]; // oldest first: nearest nodes come out first visit(node); for (const next of graph[node]) { if (seen.has(next)) continue; seen.add(next); queue.push(next); } }}dfs.js
function dfs(graph, start) { const stack = [start]; const seen = new Set(); while (stack.length) { const node = stack.pop(); // newest first: keeps going deeper if (seen.has(node)) continue; seen.add(node); visit(node); // reversed, so the first neighbor is popped first for (const next of [...graph[node]].reverse()) { if (!seen.has(next)) stack.push(next); } }}Draw walls, then search only BFS promises the shortest path
Grid Click cells to toggle walls
path length
cells visited
Shortest by number of edges. Once edges have weights, like road distances, you need Dijkstra
path.js
// remember who discovered each cellparent.set(next, node); // walk back from the goal to the startconst path = [];for (let at = goal; at !== undefined; at = parent.get(at)) { path.unshift(at);}Topics
Next: How database transactions work
Open lesson