Graphs · Exercise 39 of 100
Shortest paths with BFS
Breadth-first search uses a queue to explore vertices in order of their distance from the start. When every edge counts as one step, the first visit to a vertex gives the fewest steps needed to reach it.
Try it yourself
Walking trails go both ways and connect Gate to Oak, Gate to Elm, Oak to Pond, Pond to Tower and Elm to Tower. Starting at Gate, how many trails are in a shortest route to Tower?
One-step hint
Give Gate distance zero. Label all towns one trail away before expanding any of them, and record Tower's label when you first reach it.
Worked solution
- From Gate, the first layer contains Oak and Elm. Tower is not in this layer.
- Elm reaches Tower in the next layer, so the route through Elm takes 2 trails.