What is Dijkstra's algorithm?
An algorithm that finds the shortest paths from one starting vertex to every vertex in a graph whose edge weights are 0 or greater. It repeatedly finalizes the nearest vertex whose distance is not yet final and updates the distances of its neighbors. It does not work correctly with negative edge weights.
Japanese name: ダイクストラ法
Dijkstra's algorithm appears in 3 practice questions across 1 topic, including Data Structures and Algorithms.
Field: Data Structures and Algorithms
Negative weights and other algorithms
Dijkstra's algorithm finalizes vertices on the assumption that going through other vertices can only increase a distance, never decrease it. With negative edges, a finalized distance can later become shorter, so correct answers are not guaranteed. When negative weights exist, the Bellman-Ford algorithm, which relaxes every edge V−1 times, is used; it can also detect negative cycles. For shortest paths between all pairs of vertices, the Floyd-Warshall algorithm (O(V³)), based on dynamic programming, is also used. In network routing, link-state protocols such as OSPF use Dijkstra's algorithm in each router to compute routes.
FAQ
How is Dijkstra's algorithm related to breadth-first search?
If every edge has weight 1, Dijkstra's algorithm finalizes vertices in the same order as breadth-first search. It can be seen as a generalization for different weights that replaces the queue with a priority queue returning the smallest distance first.
Can Dijkstra's algorithm be used on directed graphs?
Yes. As long as the weights are 0 or greater, it finds correct shortest paths in directed and undirected graphs, including graphs with cycles.