Why BFS stops working
After this: Show a graph where the path with the fewest edges is not the cheapest.
On this page · 7 sections · 3 checks
In the last lesson you saw that counting roads can give the wrong answer. Now we look at a real algorithm that counts: BFS. You met it in the graphs tutorial as the way to find a shortest path. This lesson shows why it stops working once edges have weights.
What BFS measures
BFS stands for breadth-first search. It starts at one node and works outward in layers. First it visits every node one edge away. Then it visits every node two edges away, and so on. It gives each node a label: the number of edges from the start.
So BFS answers the question "what is the smallest number of edges?". It never reads a weight.
Three nodes first
Here are the three nodes from the last lesson.
Run BFS from A.
- A is the start, so its label is 0.
- B and C are both one edge from A, so each gets the label 1.
- BFS comes to C and sees the edge C→B. B already has a label, so BFS ignores this edge.
BFS has found the path A→B, which costs 4. The path A → C → B costs 1 + 2 = 3, but BFS has no way to prefer it, because that path has more edges.
Five nodes
The same thing happens on the full graph. This table compares what BFS measures with the true cheapest cost from A.
| Node | BFS label (fewest edges) | Cheapest cost (adding weights) |
|---|---|---|
| A | 0 | 0 |
| B | 1 | 3 |
| C | 1 | 1 |
| D | 2 | 4 |
| E | 3 | 7 |
Now look at the node E. There are three paths from A to E.
| Path | Edges | Cost |
|---|---|---|
| A → B → D → E | 3 | 4 + 1 + 3 = 8 |
| A → C → D → E | 3 | 1 + 5 + 3 = 9 |
| A → C → B → D → E | 4 | 1 + 2 + 1 + 3 = 7 |
BFS finds A → B → D → E. It has the fewest edges, the same as A → C → D → E, and BFS takes it because B comes first in A's list. The cheapest path has one more edge and costs 1 less. The error starts at B: BFS reaches B through the direct edge, and every path built on top of that keeps the extra cost.
BFS is sure to find the cheapest path only when every edge costs the same. Then counting edges and adding weights give the same answer.
The code
Here is BFS with a second function that adds up the cost of a path.
from collections import deque
def bfs_path(graph, start, goal): parents = {start: None} queue = deque([start]) while queue: node = queue.popleft() for next_node, weight in graph[node]: # the weight is never read: BFS counts edges if next_node not in parents: parents[next_node] = node queue.append(next_node) if goal not in parents: return None path = [] node = goal while node is not None: path.append(node) node = parents[node] return path[::-1]
def path_cost(graph, path): total = 0 for a, b in zip(path, path[1:]): total += dict(graph[a])[b] # the weight of the edge a -> b return totalimport java.util.*;
public class Bfs { static List<String> bfsPath(Map<String, List<Edge>> graph, String start, String goal) { Map<String, String> parents = new HashMap<>(); parents.put(start, null); Deque<String> queue = new ArrayDeque<>(); queue.add(start); while (!queue.isEmpty()) { String node = queue.poll(); for (Edge e : graph.get(node)) { // the weight is never read: BFS counts edges if (!parents.containsKey(e.to())) { parents.put(e.to(), node); queue.add(e.to()); } } } if (!parents.containsKey(goal)) return null; LinkedList<String> path = new LinkedList<>(); for (String node = goal; node != null; node = parents.get(node)) path.addFirst(node); return path; }
static int pathCost(Map<String, List<Edge>> graph, List<String> path) { int total = 0; for (int i = 0; i + 1 < path.size(); i++) { for (Edge e : graph.get(path.get(i))) { if (e.to().equals(path.get(i + 1))) total += e.weight(); // the weight of the edge a -> b } } return total; }}Here is how to read it.
parentsrecords the node that each node was reached from. A node that appears inparentshas already been seen.- The
whileloop is BFS. It takes the node at the front of the queue, then adds each neighbour that has not been seen yet. - The comment in the loop marks the key point: the weight is there in the data, but the code never reads it.
- After the loop, the code walks back through
parentsto build the path. A later lesson explains this walk. - path_costpathCost adds up the weight of each edge along a path.
Now we use it to find the path, and we compare its cost with the path it missed.
path = bfs_path(graph, "A", "E")print(" -> ".join(path), "costs", path_cost(graph, path))print("A -> C -> B -> D -> E costs", path_cost(graph, ["A", "C", "B", "D", "E"]))A -> B -> D -> E costs 8 A -> C -> B -> D -> E costs 7
List<String> path = Bfs.bfsPath(graph, "A", "E");System.out.println(String.join(" -> ", path) + " costs " + Bfs.pathCost(graph, path));System.out.println("A -> C -> B -> D -> E costs " + Bfs.pathCost(graph, List.of("A", "C", "B", "D", "E")));A -> B -> D -> E costs 8 A -> C -> B -> D -> E costs 7
Watch it happen
Run BFS from A, then run Dijkstra's algorithm from A. Dijkstra's algorithm is the subject of the next lesson. For now, compare the labels under the nodes.
- BFS from ABFS from A. The labels count edges: B 1, C 1, D 2, E 3.
- Dijkstra from A
Pick a start node and run an algorithm.
Check yourself
BFS from A reaches E in three edges, along A → B → D → E, which costs 8. Is that the cheapest route from A to E?
BFS labels B with 1. Dijkstra's algorithm labels B with 3. Why do they disagree?
When can you rely on BFS to find the cheapest path in a weighted graph?
Connect
- Say that BFS counts edges, so it is sure to find the cheapest path only when every edge costs the same.
- Show the graph where the fewest edges loses: three edges cost 8, and four edges cost 7.