Shortest Path: Unweighted Graph
- Formally describe the shortest path problem.
- Recognize that (unweighted) shortest path algorithm is a modified BFS.
Let us formally define the shortest path problem:
Shortest Path Problem
Input: Graph , and a starting vertex .
Goal: Identify a shortest path from to every vertex in .
Note we are considering the length of a path here. In other words, "shortest path" means "shortest length." (We will soon contrast this with the case where shortest path means shortest cost.)
Lemma: Let be a directed or undirected graph. At the conclusion of the modified BFS, for every vertex , the value
distance[v]
equals the length of a shortest path from to in (or if no such path exists).
This is not the case for DFS!
Why does BFS find the shortest path?
Okay! Let's think about this problem for a moment. We have a source vertex and a target vertex . We want a shortest path from to (if exists). What can we do? Well, we can look at all the vertices that are one edge away from ; if we find , we are done. If not, we can look at all vertices that are two edges away from , then those that are three edges away from , and so on until we find . This strategy is what BFS is doing! It explores all (reachable) vertices that are edges away from the source vertex before visiting any vertex edges away. So, if there are multiple paths to , and one returned by BFS has edges, that path is the shortest. If there was a shorter path with, e.g., length of , then would have been explored before exploring vertices that are edges away from the source.
For a formal proof, refer to CLRS, Third Edition, Lemma 22.2 on page 598.
Resources
- Wikipedia's entry on Shortest Path Problem.