Breadth-First
Search
Explore a graph level by level using a queue. BFS guarantees the shortest path in unweighted graphs and is the backbone of social network friend-finding, GPS navigation, and AI game solving (Pac-Man, Chess openings).
How does breadth-first search (BFS) work?
BFS explores a graph level by level: first the start node's neighbours, then their neighbours, and so on. It uses a queue and a visited set. Because it reaches nodes in order of distance, BFS finds the shortest path (fewest edges) in an unweighted graph. It runs in O(V + E).
function shortestPath(graph, start, goal) {
const queue = [[start]], visited = new Set([start]);
while (queue.length) {
const path = queue.shift(), node = path.at(-1);
if (node === goal) return path;
for (const next of graph[node] ?? []) {
if (!visited.has(next)) { visited.add(next); queue.push([...path, next]); }
}
}
return null;
}Level-by-level traversal — animated
// Array state
// Pseudocode
Key principles
Use a queue — FIFO guarantees level order
BFS uses a queue (FIFO). Dequeue a node, process it, then enqueue all unvisited neighbors. Because neighbors are enqueued after the current level's nodes, all level-k nodes are processed before any level-(k+1) node.
BFS traversal
1function bfs(graph, start):2 queue = Queue([start]) // FIFO — process level by level3 visited = Set([start])4 order = []56 while queue not empty:7 node = queue.dequeue() // O(1)8 order.append(node)910 for neighbor in graph[node]:11 if neighbor not in visited:12 visited.add(neighbor)13 queue.enqueue(neighbor)1415 return order // level-by-level
Shortest path variant
1// BFS shortest path — unweighted graph2function shortestPath(graph, src, dst):3 queue = Queue([(src, [src])])4 visited = Set([src])56 while queue not empty:7 (node, path) = queue.dequeue()8 if node == dst: return path910 for neighbor in graph[node]:11 if neighbor not in visited:12 visited.add(neighbor)13 queue.enqueue((neighbor, path + [neighbor]))1415 return [] // no path found
Complexity
O(V + E) time
O(V) time
Constant time
🎯 Quick Check
BFS explores node X and enqueues its neighbors Y and Z. Which is processed next?
Breadth-First Search: summary
Key points
- Mark nodes visited when you enqueue them, not when you dequeue them, to avoid duplicates.
- On grids, treat each cell as a node with up to 4 neighbours.
- For weighted edges, use Dijkstra's algorithm instead.
Frequently asked questions
›BFS vs DFS?
BFS uses a queue and finds shortest paths in unweighted graphs. DFS uses a stack or recursion and goes deep first, which suits cycle detection, topological sorting and exploring all paths.