Graph Traversal (BFS & DFS)
Breadth-first and depth-first search — the two ways to explore any graph, and the dozens of problems they solve.
Almost every graph algorithm is built on one of two traversals. Both visit every reachable vertex and edge once: O(V + E).
- Uses a queue (FIFO)
- Explores in layers by distance from the source
- Finds shortest paths in unweighted graphs
- Memory: O(width of the frontier)
- Uses a stack or recursion (LIFO)
- Goes as deep as possible, then backtracks
- Cycle detection, topological sort, components, path existence
- Memory: O(depth)
Step through both on the same graph:
BFS
Mark a vertex visited when you enqueue it, not when you dequeue it — otherwise the same vertex can be enqueued many times.
// Shortest distance (in edges) from src to every vertex
int[] bfs(List<List<Integer>> adj, int src) {
int[] dist = new int[adj.size()];
Arrays.fill(dist, -1);
Deque<Integer> q = new ArrayDeque<>();
dist[src] = 0;
q.offer(src);
while (!q.isEmpty()) {
int u = q.poll();
for (int v : adj.get(u)) {
if (dist[v] == -1) { // unvisited
dist[v] = dist[u] + 1; // mark on enqueue
q.offer(v);
}
}
}
return dist;
}from collections import deque
def bfs(adj, src):
dist = {src: 0}
q = deque([src])
while q:
u = q.popleft()
for v in adj[u]:
if v not in dist: # unvisited
dist[v] = dist[u] + 1 # mark on enqueue
q.append(v)
return distfunction bfs(adj: number[][], src: number): number[] {
const dist = new Array(adj.length).fill(-1);
const q = [src];
dist[src] = 0;
for (let head = 0; head < q.length; head++) { // index pointer: O(1) dequeue
const u = q[head];
for (const v of adj[u]) {
if (dist[v] === -1) { dist[v] = dist[u] + 1; q.push(v); }
}
}
return dist;
}BFS on a grid
Grids are implicit graphs: each cell's neighbours are the 4 (or 8) adjacent cells. Use a direction array.
int shortestPath(int[][] grid) { // 0 = open, 1 = wall
int R = grid.length, C = grid[0].length;
int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
int[][] dist = new int[R][C];
for (int[] row : dist) Arrays.fill(row, -1);
Deque<int[]> q = new ArrayDeque<>();
q.offer(new int[]{0, 0});
dist[0][0] = 0;
while (!q.isEmpty()) {
int[] p = q.poll();
if (p[0] == R - 1 && p[1] == C - 1) return dist[p[0]][p[1]];
for (int[] d : dirs) {
int r = p[0] + d[0], c = p[1] + d[1];
if (r >= 0 && r < R && c >= 0 && c < C && grid[r][c] == 0 && dist[r][c] == -1) {
dist[r][c] = dist[p[0]][p[1]] + 1;
q.offer(new int[]{r, c});
}
}
}
return -1;
}from collections import deque
def shortest_path(grid):
R, C = len(grid), len(grid[0])
dist = {(0, 0): 0}
q = deque([(0, 0)])
while q:
r, c = q.popleft()
if (r, c) == (R - 1, C - 1):
return dist[(r, c)]
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 0 and (nr, nc) not in dist:
dist[(nr, nc)] = dist[(r, c)] + 1
q.append((nr, nc))
return -1function shortestPath(grid: number[][]): number {
const R = grid.length, C = grid[0].length;
const dist = grid.map((row) => row.map(() => -1));
const q: [number, number][] = [[0, 0]];
dist[0][0] = 0;
for (let h = 0; h < q.length; h++) {
const [r, c] = q[h];
if (r === R - 1 && c === C - 1) return dist[r][c];
for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] === 0 && dist[nr][nc] === -1) {
dist[nr][nc] = dist[r][c] + 1;
q.push([nr, nc]);
}
}
}
return -1;
}Multi-source BFS: start with all sources in the queue at distance 0 — "rotting oranges", "distance to nearest 0", "walls and gates". 0-1 BFS: edges weigh 0 or 1 → use a deque, push 0-edges to the front.
DFS
// Count connected components
int countComponents(int n, List<List<Integer>> adj) {
boolean[] seen = new boolean[n];
int comps = 0;
for (int s = 0; s < n; s++) {
if (seen[s]) continue;
comps++;
dfs(s, adj, seen);
}
return comps;
}
void dfs(int u, List<List<Integer>> adj, boolean[] seen) {
seen[u] = true;
for (int v : adj.get(u)) if (!seen[v]) dfs(v, adj, seen);
}def count_components(n, adj):
seen = [False] * n
def dfs(u):
seen[u] = True
for v in adj[u]:
if not seen[v]:
dfs(v)
comps = 0
for s in range(n):
if not seen[s]:
comps += 1
dfs(s)
return comps
# Deep graphs: raise sys.setrecursionlimit or use an explicit stack.function countComponents(n: number, adj: number[][]): number {
const seen = new Array(n).fill(false);
const dfs = (u: number) => {
seen[u] = true;
for (const v of adj[u]) if (!seen[v]) dfs(v);
};
let comps = 0;
for (let s = 0; s < n; s++) if (!seen[s]) { comps++; dfs(s); }
return comps;
}Cycle detection in a directed graph (three colours)
White = unvisited, grey = on the current recursion path, black = finished. An edge to a grey vertex is a back edge → cycle.
boolean hasCycle(List<List<Integer>> adj) {
int[] color = new int[adj.size()]; // 0 white, 1 grey, 2 black
for (int u = 0; u < adj.size(); u++)
if (color[u] == 0 && dfsCycle(u, adj, color)) return true;
return false;
}
boolean dfsCycle(int u, List<List<Integer>> adj, int[] color) {
color[u] = 1;
for (int v : adj.get(u)) {
if (color[v] == 1) return true; // back edge
if (color[v] == 0 && dfsCycle(v, adj, color)) return true;
}
color[u] = 2;
return false;
}def has_cycle(adj):
WHITE, GREY, BLACK = 0, 1, 2
color = [WHITE] * len(adj)
def dfs(u):
color[u] = GREY
for v in adj[u]:
if color[v] == GREY:
return True # back edge
if color[v] == WHITE and dfs(v):
return True
color[u] = BLACK
return False
return any(color[u] == WHITE and dfs(u) for u in range(len(adj)))function hasCycle(adj: number[][]): boolean {
const color = new Array(adj.length).fill(0); // 0 white, 1 grey, 2 black
const dfs = (u: number): boolean => {
color[u] = 1;
for (const v of adj[u]) {
if (color[v] === 1) return true;
if (color[v] === 0 && dfs(v)) return true;
}
color[u] = 2;
return false;
};
return adj.some((_, u) => color[u] === 0 && dfs(u));
}What each traversal is for
| Task | Use |
|---|---|
| Shortest path, unweighted | BFS |
| Level-by-level processing | BFS |
| Connected components / flood fill | Either (DFS is shortest to write) |
| Cycle detection (directed) | DFS with colours |
| Topological order | DFS post-order or Kahn's BFS |
| Bipartite check | BFS/DFS 2-colouring |
| Bridges / articulation points | DFS with discovery times (Tarjan) |
| Strongly connected components | DFS (Kosaraju / Tarjan) |
- BFS = queue = layers = unweighted shortest paths.
- DFS = stack/recursion = deep first = cycles, ordering, components.
- Both are O(V + E); always track visited vertices.
- Grids and state spaces are implicit graphs — generate neighbours on the fly.
QWord ladder: shortest transformation from beginWord to endWord changing one letter at a time.hard
BFS over words. Neighbours of a word: change each position to a–z and keep results in the dictionary set (remove them when enqueued). O(N · L · 26). Bidirectional BFS from both ends roughly square-roots the explored frontier.
QClone a graph.medium
BFS/DFS with a map from original node to its clone. On visiting a neighbour, create its clone if missing and add it to the current clone's neighbour list. The map doubles as the visited set.
QWhy is DFS not suitable for shortest paths?easy
DFS may reach a vertex first via a long path; nothing guarantees the first visit is the shortest. BFS processes vertices in nondecreasing distance order, so the first visit is optimal (for unweighted edges).