Data Structures and Algorithms
Which condition on the graph is required for Dijkstra's algorithm to find correct shortest paths?
- AThe graph has no cycles (paths that return to the same vertex)
- BThe edges have no direction
- CAll edge weights are 0 or greater
Show answer and explanation
Answer: C. All edge weights are 0 or greater
Dijkstra's algorithm finalizes the unfinalized vertex with the smallest distance. This relies on the assumption that going through other vertices can only increase a distance, never decrease it. With a negative edge, a distance can become shorter later through another route; for example, in a directed graph with S→A 2, S→B 3 and B→A −2, A is finalized at 2 before the path S→B→A of length 1 is found. When negative weights exist, the Bellman-Ford algorithm or similar methods are used. Dijkstra's algorithm works with cycles and with directed edges as long as all weights are 0 or greater.
- A. It works correctly with cycles as long as the weights are 0 or greater; road networks are full of cycles.
- B. It also works on directed graphs.
- C. Correct. With negative weights, a finalized distance can later turn out to be shorter.