Definition (Breadth First Search)
Breadth First Search (BFS) connects each new vertex to the oldest possible option. This is the opposite of Depth First Search. The BFS tree creates a wide graph. Using the same example,
graph LR; 1((1)) o--o 2((2)); 1((1)) o--o 3((3)); 2((2)) o--o 3((3)); 1((1)) o--o 7((7)); 2((2)) o--o 6((6)); 3((3)) o--o 4((4)); 3((3)) o--o 5((5)); 3((3)) o--o 7((7)); 4((4)) o--o 5((5)); 8((8)) o--o 4((4)); 4((4)) o--o 7((7)); 8((8)) o--o 5((5)); 5((5)) o--o 6((6)); 6((6)) o--o 7((7));
we get the BFS to be
graph LR; 1((1)) o--o 2((2)); 1 o--o 4((4)); 1 o--o 3((3)); 2 o--o 5((5)); 3 o--o 6((6)); 3 o--o 7((7)); 6 o--o 8((8));
This generated by . Then since we visited the earliest (and thus the oldest visited), we have . Backtracking, and then , and so on.
Lemma (BFS Has No Ancestor Edges)
No ancestor edges are in the edges since they’re all cousins.
Proof: We always connect to older vertices.
graph LR; a((a)) o--o b((b)); b o--o c((c)); a o-.e.-o c;
Here, we will always go for to , and then always take .
Theorem (BFS Gives Shortest Path)
If you run BFS starting from vertex to get tree , then the path from for any other vertex in is the shortest path between .
Proof:
Fix . Let be the true shortest path length (minimum number of edges) from to in the graph , where
Then let be the tree path length from to generated by BFS tree . This is also the “level” that is in (relative to ).
I claim that for any vertex . We prove this by strong induction on .
Base Cases: Let . Then iff . The BFS algorithm starts at , at level of , so holds.
Inductive Hypothesis: Assume that for all for some , the claim holds. That is, if then .
Let . We need to show that this claim holds for any vertex where . Then we have some path where
Since , then . By the induction hypothesis, . Thus, when BFS reaches , it considers its neighbors. When BFS sees , if is unvisited, then we set as ‘s parent, and . If is already visited, then some other node visited at some other level.
Suppose by contradiction that was visited earlier, such that . But then by the Induction Hypothesis, . But this is a contradiction, since we assumed . Therefore is visited after , and cannot be visited from a previous vertex. Thus .