Graph Traversal

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

BFS on graph {A-B,A-C,B-D,B-E,C-F}step 1/5

// Array state

A
queue
B
[1]
C
[2]
D
[3]
E
[4]
F
[5]
→ Graph: A connects to B,C. B connects to D,E. C connects to F. Start BFS at A. Enqueue A.

// Pseudocode

1function bfs(graph, start):
2 queue = Queue([start]) // FIFO — process level by level
3 visited = Set([start])
4 order = []
5 
6 while queue not empty:
7 node = queue.dequeue() // O(1)
8 order.append(node)
9 
10 for neighbor in graph[node]:
11 if neighbor not in visited:
12 visited.add(neighbor)
13 queue.enqueue(neighbor)
14 
15 return order // level-by-level

Key principles

1 / 4
1

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.

1 of 4

BFS traversal

bfs.pseudo
1function bfs(graph, start):
2 queue = Queue([start]) // FIFO — process level by level
3 visited = Set([start])
4 order = []
5 
6 while queue not empty:
7 node = queue.dequeue() // O(1)
8 order.append(node)
9 
10 for neighbor in graph[node]:
11 if neighbor not in visited:
12 visited.add(neighbor)
13 queue.enqueue(neighbor)
14 
15 return order // level-by-level

Shortest path variant

bfs-shortest-path.pseudo
1// BFS shortest path — unweighted graph
2function shortestPath(graph, src, dst):
3 queue = Queue([(src, [src])])
4 visited = Set([src])
5 
6 while queue not empty:
7 (node, path) = queue.dequeue()
8 if node == dst: return path
9 
10 for neighbor in graph[node]:
11 if neighbor not in visited:
12 visited.add(neighbor)
13 queue.enqueue((neighbor, path + [neighbor]))
14 
15 return [] // no path found

Complexity

Time — visits every vertex and edge onceO(V + E)

O(V + E) time

Space — queue holds at most one full level (width of graph)O(V)

O(V) time

Shortest path — guaranteed in unweighted graphO(1)

Constant time

🔍BFS on trees = level-order traversal
When applied to a tree (no cycles), BFS is exactly level-order traversal — the same algorithm used to print a binary tree level by level. The queue naturally handles the level grouping.
⚠️Visited set is critical
Without a visited set, BFS will loop infinitely on graphs with cycles. Always mark a node as visited the moment you enqueue it — not when you dequeue it — to avoid redundant work.

🎯 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.