BFS and DFS: Graph Traversal Explained

Introduction:
Imagine you have lost your keys somewhere in a big house. There are two natural ways to search. You could check every room on the ground floor first, then every room on the first floor, and so on, moving outwards level by level. Or you could pick one corridor and follow it as deep as it goes, into the last room at the end, and only then come back and try the next corridor.
These two strategies are the two most important algorithms for exploring a graph:
- Breadth-First Search (BFS) explores level by level, closest things first.
- Depth-First Search (DFS) goes as deep as possible along one path before backing up.
Almost every graph problem you will meet, from “how many hops between two people on a social network?” to “in what order should these tasks run?”, is solved with one of these two, often with a small twist. In this lesson we will implement both in JavaScript, see exactly how they differ, and then use them to solve seven classic problems: shortest paths, connected components, cycle detection, topological sort, number of islands, and maze solving.
This lesson builds on graph data structure, stacks and queues and recursion. All code was run with Node.js, and the comments show the real output.
Part 1: The Setup
1. Our Example Graph:
We’ll store the graph as an adjacency list: an object where each node maps to the list of its neighbours. This is the most common way to represent a graph in code because it is compact and makes “who are my neighbours?” instant.
const graph = {
A: ["B", "C"],
B: ["A", "D", "E"],
C: ["A", "F"],
D: ["B"],
E: ["B", "F"],
F: ["C", "E", "G"],
G: ["F"],
};
Drawn as a picture, it looks like this (each line is a two-way connection):
A
/ \
B C
/ \ \
D E---F
|
G
2. The Visited Set:
Both BFS and DFS share one essential idea: remember which nodes you have already seen. Unlike a tree, a graph can have cycles. A goes to B, B goes back to A. Without a visited set, the search would bounce between A and B forever.
The only real difference between the two algorithms is the order in which they pick the next node to explore:
- BFS uses a queue (first in, first out): explore the oldest discovered node next.
- DFS uses a stack (last in, first out), or recursion, which uses the call stack: explore the newest discovered node next.
Part 2: Breadth-First Search
3. BFS Implementation:
BFS starts at one node, visits all its neighbours, then all their neighbours, and so on, like ripples spreading out in water:
function bfs(graph, start) {
const visited = new Set([start]);
const queue = [start];
const order = [];
let head = 0; // index of the front of the queue
while (head < queue.length) {
const node = queue[head++]; // dequeue
order.push(node);
for (const next of graph[node]) {
if (!visited.has(next)) {
visited.add(next); // mark when discovered, not when visited
queue.push(next); // enqueue
}
}
}
return order;
}
console.log(bfs(graph, "A").join(" → "));
// A → B → C → D → E → F → G
The order is exactly level by level: A first, then its neighbours B and C, then the next level D, E and F, and finally G.
Two small details matter here:
- We use a
headindex instead ofqueue.shift().shift()removes the first element of an array and has to move every other element down, which is O(n) each time. Moving an index forward is O(1), keeping BFS fast on big graphs. - We mark a node as visited when we add it to the queue, not when we take it out. Otherwise the same node could be added to the queue several times by different neighbours.
4. Levels and Distances:
Because BFS explores in rings, the first time it reaches a node is always along the fewest edges. We can record each node’s distance from the start:
function bfsLevels(graph, start) {
const dist = { [start]: 0 };
const queue = [start];
let head = 0;
while (head < queue.length) {
const node = queue[head++];
for (const next of graph[node]) {
if (!(next in dist)) {
dist[next] = dist[node] + 1;
queue.push(next);
}
}
}
return dist;
}
console.log(bfsLevels(graph, "A"));
// { A: 0, B: 1, C: 1, D: 2, E: 2, F: 2, G: 3 }
This is how a social network can say “Sara is a 2nd-degree connection“: it is a BFS from your profile.
5. Shortest Path in an Unweighted Graph:
To get the actual path, not just the length, store each node’s parent: the node we came from when we first discovered it. Then walk backwards from the goal:
function shortestPath(graph, start, goal) {
const parent = new Map([[start, null]]);
const queue = [start];
let head = 0;
while (head < queue.length) {
const node = queue[head++];
if (node === goal) break;
for (const next of graph[node]) {
if (!parent.has(next)) {
parent.set(next, node);
queue.push(next);
}
}
}
if (!parent.has(goal)) return null; // goal not reachable
const path = [];
for (let n = goal; n !== null; n = parent.get(n)) path.push(n);
return path.reverse();
}
console.log(shortestPath(graph, "A", "G")); // [ 'A', 'C', 'F', 'G' ]
console.log(shortestPath(graph, "D", "G")); // [ 'D', 'B', 'E', 'F', 'G' ]
console.log(shortestPath({ X: ["Y"], Y: ["X"], Z: [] }, "X", "Z")); // null
From A to G there are two routes, A → B → E → F → G (4 edges) and A → C → F → G (3 edges). BFS correctly found the shorter one.
One important limit: BFS finds the shortest path only when every edge costs the same. If edges have different weights, like road distances, you need Dijkstra’s algorithm instead, which we will cover in a later lesson.
Part 3: Depth-First Search
6. Recursive DFS:
DFS dives as deep as it can before backing up. The recursive version is very short, because the call stack remembers where to come back to:
function dfs(graph, start, visited = new Set(), order = []) {
visited.add(start);
order.push(start);
for (const next of graph[start]) {
if (!visited.has(next)) dfs(graph, next, visited, order);
}
return order;
}
console.log(dfs(graph, "A").join(" → "));
// A → B → D → E → F → C → G
Compare this with BFS’s A → B → C → D → E → F → G. DFS went A → B → D, hit a dead end at D, backed up to B, went to E, then followed E → F → C (all the way round), backed up to F and finally visited G. It reached C late, even though C is A’s direct neighbour, because it was busy following the B branch to its end.
7. Iterative DFS with a Stack:
Recursion has a limit: every call uses a frame on the call stack, and JavaScript engines allow only a limited number. We built a long chain graph of 20,000 nodes (0 → 1 → 2 → … → 19999) and ran the recursive version:
dfs(chain, "0");
// RangeError: Maximum call stack size exceeded
The fix is to manage the stack yourself, with an array:
function dfsIterative(graph, start) {
const visited = new Set();
const stack = [start];
const order = [];
while (stack.length) {
const node = stack.pop();
if (visited.has(node)) continue;
visited.add(node);
order.push(node);
// push neighbours in reverse so the first neighbour is explored first
for (let i = graph[node].length - 1; i >= 0; i--) {
if (!visited.has(graph[node][i])) stack.push(graph[node][i]);
}
}
return order;
}
console.log(dfsIterative(graph, "A").join(" → ")); // A → B → D → E → F → C → G
console.log(dfsIterative(chain, "0").length); // 20000
It gives exactly the same order as the recursive version, and it handles the 20,000-node chain without trouble. Notice that this is BFS’s code with the queue swapped for a stack (and the visited check moved to when a node is popped). That single change turns “widest first” into “deepest first”.
8. Complexity:
Both BFS and DFS visit every node once and look at every edge once (twice for undirected graphs, once from each end). For a graph with V vertices and E edges:
- Time: O(V + E)
- Space: O(V) for the visited set plus the queue or stack
So neither is faster in general. The choice depends on what you want to find.
Part 4: Classic Problems
9. Connected Components:
A graph can be in several separate pieces. To find them, start a search from every node that hasn’t been visited yet; each new search discovers one whole piece:
function countComponents(graph) {
const visited = new Set();
const groups = [];
for (const node of Object.keys(graph)) {
if (visited.has(node)) continue;
const group = [];
const stack = [node];
visited.add(node);
while (stack.length) {
const n = stack.pop();
group.push(n);
for (const m of graph[n]) {
if (!visited.has(m)) { visited.add(m); stack.push(m); }
}
}
groups.push(group.sort());
}
return groups;
}
console.log(countComponents({ 1: ["2"], 2: ["1", "3"], 3: ["2"], 4: ["5"], 5: ["4"], 6: [] }));
// [ [ '1', '2', '3' ], [ '4', '5' ], [ '6' ] ]
Real uses include finding groups of friends who are all connected, or checking whether every computer in a network can reach every other one.
10. Cycle Detection in a Directed Graph:
In a directed graph (one-way edges), a cycle means you can start at a node and follow arrows back to it. This is a problem for things like course prerequisites: if HTML requires CSS and CSS requires HTML, nobody can ever start.
DFS detects this using three colours: white (not visited), gray (currently on the path we are exploring), and black (completely finished). Reaching a gray node means we have looped back onto our own path:
function hasCycle(graph) {
const WHITE = 0, GRAY = 1, BLACK = 2;
const color = {};
for (const n of Object.keys(graph)) color[n] = WHITE;
function visit(n) {
color[n] = GRAY;
for (const m of graph[n]) {
if (color[m] === GRAY) return true; // back to our own path
if (color[m] === WHITE && visit(m)) return true;
}
color[n] = BLACK;
return false;
}
return Object.keys(graph).some((n) => color[n] === WHITE && visit(n));
}
const courses = { html: ["css"], css: ["javascript"], javascript: ["react"], react: ["nextjs"], nextjs: [] };
console.log(hasCycle(courses)); // false
console.log(hasCycle({ a: ["b"], b: ["c"], c: ["a"] })); // true
Why not simply “already visited”? In a directed graph, reaching a black node is fine: it just means two paths lead to the same finished node, like two courses that both require JavaScript.
11. Topological Sort:
If a directed graph has no cycles, we can put its nodes in an order where every arrow points forward: each task comes after everything it depends on. This is called a topological sort, and DFS gives it almost for free. When a node is finished (all its descendants are done), add it to a list; the reversed list is the answer:
function topoSort(graph) {
const visited = new Set();
const out = [];
function visit(n) {
visited.add(n);
for (const m of graph[n]) if (!visited.has(m)) visit(m);
out.push(n); // all of n's dependants are already in out
}
for (const n of Object.keys(graph)) if (!visited.has(n)) visit(n);
return out.reverse();
}
console.log(topoSort({
nextjs: [], react: ["nextjs"], javascript: ["react", "node"],
node: ["express"], express: [], html: ["css", "javascript"], css: ["javascript"],
}));
// [ 'html', 'css', 'javascript', 'node', 'express', 'react', 'nextjs' ]
Here an arrow x → y means “learn x before y”. The result is a valid learning order: HTML, then CSS, then JavaScript, and only then Node, Express, React and Next.js. Build tools (deciding which files to compile first), package managers (installing dependencies before the packages that need them) and spreadsheets (recalculating cells in the right order) all use topological sorting.
12. Number of Islands (DFS on a Grid):
Many problems hide a graph inside a 2D grid: each cell is a node, connected to its neighbours up, down, left and right. In this famous interview question, 1 is land and 0 is water. How many separate islands are there?
function numIslands(grid) {
const rows = grid.length, cols = grid[0].length;
const seen = grid.map((r) => r.map(() => false));
let count = 0;
function sink(r, c) {
if (r < 0 || c < 0 || r >= rows || c >= cols) return; // off the map
if (grid[r][c] !== "1" || seen[r][c]) return; // water or done
seen[r][c] = true;
sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);
}
for (let r = 0; r < rows; r++)
for (let c = 0; c < cols; c++)
if (grid[r][c] === "1" && !seen[r][c]) { count++; sink(r, c); }
return count;
}
const map = ["11000",
"11000",
"00100",
"00011"].map((s) => s.split(""));
console.log(numIslands(map)); // 3
Each time we find unvisited land, we’ve found a new island, and DFS “sinks” the whole island so it isn’t counted again. This is exactly the connected components idea from section 9, on a grid. The same technique powers the paint bucket (flood fill) tool in image editors.
13. Shortest Path in a Maze (BFS on a Grid):
For the fewest steps through a maze, we need BFS. S is the start, E the exit, # a wall:
function solveMaze(maze) {
const rows = maze.length, cols = maze[0].length;
let start, end;
maze.forEach((row, r) => [...row].forEach((ch, c) => {
if (ch === "S") start = [r, c];
if (ch === "E") end = [r, c];
}));
const dist = maze.map((row) => [...row].map(() => -1));
dist[start[0]][start[1]] = 0;
const queue = [start];
let head = 0;
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
while (head < queue.length) {
const [r, c] = queue[head++];
if (r === end[0] && c === end[1]) return dist[r][c];
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < rows && nc < cols &&
maze[nr][nc] !== "#" && dist[nr][nc] === -1) {
dist[nr][nc] = dist[r][c] + 1;
queue.push([nr, nc]);
}
}
}
return -1; // no way out
}
console.log(solveMaze([
"S.#.....",
".##.###.",
"....#...",
"##.##.#.",
"...#..#E",
])); // 15
console.log(solveMaze(["S#E"])); // -1
The shortest route takes 15 steps, and a wall between start and exit correctly gives -1. DFS would also find a way out, but not necessarily the shortest one. Game characters finding their way around a map and robots planning a route use this idea (often extended into A* search).
Part 5: Choosing Between Them
14. BFS or DFS?:
Use BFS when:
- You need the shortest path or fewest steps in an unweighted graph (mazes, social “degrees of separation”, minimum moves in a puzzle).
- You want to process things level by level, such as all friends, then friends of friends.
- The answer is likely to be close to the start, so you don’t want to wander deep down a wrong branch.
Use DFS when:
- You need to explore everything and the order doesn’t matter (components, islands, flood fill).
- The problem is about paths and structure: cycle detection, topological sort, finding all possible routes, or solving puzzles with backtracking (Sudoku, N-Queens).
- Memory is tight on a very wide graph. BFS’s queue can hold a whole level, which can be huge; DFS only holds the current path.
And remember the practical warning from section 7: on very deep graphs, use an explicit stack instead of recursion.
Conclusion:
BFS and DFS are two ways to visit every node of a graph exactly once, in O(V + E) time. BFS uses a queue and moves outwards in rings, which makes it the tool for shortest paths in unweighted graphs: it found A → C → F → G and the 15-step way out of our maze. DFS uses a stack or recursion and follows each path to its end, which makes it ideal for exploring structure: we used it to find connected components, count islands, detect cycles with three colours, and produce a valid learning order with topological sort. We also saw why a visited set is essential, why queue.shift() is slow, and how deep recursion can overflow the call stack.
In the next lesson we will learn greedy algorithms, which build a solution by always making the choice that looks best right now, and learn when that simple strategy is actually correct.


