Graphs · Exercise 40 of 100
Dijkstra’s shortest paths
For edges with nonnegative costs, Dijkstra’s algorithm repeatedly chooses the unfinished vertex with the lowest known cost from the start. That cost is final because extending a route cannot make it cheaper. Check each outgoing edge to see whether going through the chosen vertex improves its neighbor's cost.
Try it yourself
The one-way fares are S to A for 8, S to B for 3, B to A for 2, B to T for 9 and A to T for 4. What is the cheapest total fare from S to T?
One-step hint
Keep a cheapest-known fare beside each stop. When you reach B, check whether going through it improves the fare already written beside A.
Worked solution
- After starting at S, choose B at cost 3. Going through B lowers A to 5 and gives T a first cost of 12.
- Choose A at cost 5 next. Its fare of 4 lowers T to 9, and T is the only unfinished stop.