Dijkstra's Algorithm finds the shortest path from a source node to all other nodes in a graph with non-negative weights. It uses a priority queue to explore nodes in order of increasing distance. This algorithm works by maintaining a set of visited nodes and, at each step, selecting the unvisited node with the smallest known distance to visit next. This process continues until all nodes have been visited, making it essential for network routing problems. Unlike MST algorithms, Dijkstra’s focuses on optimal paths from a single source.
dist = map vertex -> Infinity
dist[src] = 0
heap = new MinHeap()
heap.insert(src, 0)
while heap is not empty:
(u, d) = heap.extract()
if u is not visited:
relax(u, d)
function relax(u, d):
mark u as visited
for each neighbor v of u:
alt = d + weight(u, v)
if alt < dist[v]:
dist[v] = alt
heap.insert(v, alt)
(5 credits)
Dijkstra's algorithm makes a greedy assumption: once a node is popped from the Min-Priority Queue, its shortest distance is finalized and will never decrease. A negative edge encountered later could reveal a shorter path to an already finalized node, invalidating Dijkstra's greedy guarantee.
Min-Heap implementation: O((V + E) log V). Unsorted Array implementation: O(V²). Array implementation is actually faster for complete/extremely dense graphs where E ≈ V², while Min-Heap excels on sparse graphs.
Raw Dijkstra is too slow on worldwide road networks. GPS systems use A* Search with geometric heuristics, Contraction Hierarchies (CH), and Multi-Level Dijkstra to precompute highway routes and answer shortest path queries in milliseconds.
Sign in to join the discussion
Hand-picked resources to deepen your understanding
© 2025 See Algorithms. Code licensed under MIT, content under CC BY-NC 4.0