Dijkstra
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Dijkstra finds the cheapest way from one place to every other place when links have different positive costs, such as distance, time or price. It always settles the closest unsettled place next, so each answer is final when chosen.
Practical use cases
- Web app: Delivery fee and time estimate. A food-delivery app needs the quickest road route from the restaurant to your door, where each road segment has a travel time. Dijkstra tries the nearest junctions first and fixes their best time, until the customer address is reached. The ETA shown on screen comes straight from this total.
- Web app: Cheapest flight with connections. A travel site treats airports as nodes and flights as links with prices. Searching "Delhi to Goa" finds the cheapest combination of direct and connecting flights, instead of just the one with fewest legs.
- Web app: Store locator with real distance. A "nearest branch by road" button should use driving distance, not straight-line distance. Running Dijkstra from the user and stopping at the first branch reached gives the genuinely closest one.
- System: Network routing and game pathfinding. Internet routers using OSPF compute cheapest paths in this way, and games move characters around obstacles with the same idea, often sped up with an educated guess about direction. In every case the idea is the same: settle the closest unfinished place, then check if it offers a cheaper way to its neighbours.
The story: Raju Finds the Cheapest Delivery Route
Raju started delivering tiffins from his chai stall to offices across the city. Every road had a different toll or fuel cost. "Which route costs the least to each office?" he wondered. Counting stops (BFS) no longer worked: a road with one stop can be more expensive than three short ones.
Mira suggested a patient method. "Write 'unknown' on every office, and 0 on the stall. Then repeat: pick the cheapest office you have a number for and lock it in. Nobody else can reach it cheaper, since every other road starts from something that already costs at least as much."
After locking an office, look at its roads. If going through it gives a cheaper number for a neighbour, replace the neighbour's number. Raju did this again and again, always locking the cheapest open one next.
When every office was locked, each held its cheapest cost from the stall. Raju had just run Dijkstra's algorithm. It works because costs never go below zero: adding another road can never make a trip cheaper.
How to spot this problem, and where you need it
You need the cheapest or fastest route between places, but links have different costs such as minutes, kilometres or rupees, so counting steps is no longer enough.
Signs you need it
- Each link has a number on it (distance, time, fee), all of them zero or positive, and you want the smallest total.
- A BFS gives a route with few stops but it is slow or expensive because it uses long links.
- The wording is "cheapest", "fastest", "least cost" or "shortest distance" on a weighted map.
Where to use it in a project
- ETA and routing for delivery, cab or logistics features using road segments with travel times.
- Fare and itinerary search in booking sites, where each leg has a price.
The solution
Give the start a cost of 0 and every other node infinity. Keep a priority queue (a waiting line where the smallest cost always comes out first). Take the cheapest node out, then for each neighbour check if going through this node is cheaper than its current cost; if so, update it and add it to the queue. When a node comes out, its cost is final. Stop when the destination comes out.
Payoff: Before: a route with fewest roads that takes 48 minutes. After: the true fastest route at 31 minutes, found in a fraction of a second.
Explain it like I am 8
Like a greedy shopper. Always go to the closest unvisited shop you know about, and once you reach it you are sure that is the cheapest way there. From that shop, see if any other shop became cheaper to reach, and update the price tags.
How it works, step by step
- Set every distance to infinity except the start, which is 0. Put the start in a priority queue (min-heap) keyed by distance.
- Pop the vertex with the smallest distance. If it is stale (a better distance was found since), skip it. Its distance is now final.
- Relax each outgoing edge: if
dist[u] + weight < dist[v], updatedist[v]and pushvin the heap. - Repeat until the queue is empty.
- Works only for non-negative weights. With negative edges, use Bellman-Ford.
The code in four languages
PHP
<?php
// graph: node => [neighbour => weight]. Returns the cheapest cost to every node.
function dijkstra(array $graph, string $src): array {
$dist = array_fill_keys(array_keys($graph), INF);
$dist[$src] = 0;
$pq = new SplPriorityQueue();
$pq->setExtractFlags(SplPriorityQueue::EXTR_BOTH); // give back value AND priority
$pq->insert($src, 0); // higher priority pops first, so use -cost
while (!$pq->isEmpty()) {
$top = $pq->extract();
$u = $top['data'];
$d = -$top['priority'];
if ($d > $dist[$u]) continue; // stale entry: a better one was found
foreach ($graph[$u] as $v => $w) {
if ($d + $w < $dist[$v]) { // relax the road
$dist[$v] = $d + $w;
$pq->insert($v, -$dist[$v]);
}
}
}
return $dist;
}
$graph = [
'A' => ['B' => 4, 'C' => 1],
'B' => ['A' => 4, 'C' => 2, 'D' => 1],
'C' => ['A' => 1, 'B' => 2, 'D' => 5],
'D' => ['B' => 1, 'C' => 5, 'E' => 3],
'E' => ['D' => 3],
];
foreach (dijkstra($graph, 'A') as $node => $cost) echo "$node: $cost\n";JavaScript
// graph: node -> { neighbour: weight }. Returns the cheapest cost to every node.
class MinHeap {
constructor() { this.a = []; }
get size() { return this.a.length; }
push(item) { // item = [priority, value]
const a = this.a; a.push(item);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (a[p][0] <= a[i][0]) break;
[a[p], a[i]] = [a[i], a[p]]; i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length) {
a[0] = last; let i = 0;
for (;;) {
const l = 2 * i + 1, r = l + 1; let m = i;
if (l < a.length && a[l][0] < a[m][0]) m = l;
if (r < a.length && a[r][0] < a[m][0]) m = r;
if (m === i) break;
[a[m], a[i]] = [a[i], a[m]]; i = m;
}
}
return top;
}
}
function dijkstra(graph, src) {
const dist = {};
for (const n of Object.keys(graph)) dist[n] = Infinity;
dist[src] = 0;
const pq = new MinHeap();
pq.push([0, src]);
while (pq.size) {
const [d, u] = pq.pop();
if (d > dist[u]) continue; // stale entry: a better one was found
for (const [v, w] of Object.entries(graph[u])) {
if (d + w < dist[v]) { // relax the road
dist[v] = d + w;
pq.push([dist[v], v]);
}
}
}
return dist;
}
const graph = {
A: { B: 4, C: 1 },
B: { A: 4, C: 2, D: 1 },
C: { A: 1, B: 2, D: 5 },
D: { B: 1, C: 5, E: 3 },
E: { D: 3 },
};
for (const [node, cost] of Object.entries(dijkstra(graph, 'A'))) console.log(node + ': ' + cost);Java
import java.util.*;
public class Main {
// graph: node -> {neighbour: weight}. Returns the cheapest cost to every node.
static Map<String, Integer> dijkstra(Map<String, Map<String, Integer>> graph, String src) {
Map<String, Integer> dist = new TreeMap<>();
for (String n : graph.keySet()) dist.put(n, Integer.MAX_VALUE); // "infinity"
dist.put(src, 0);
// The queue hands back the cheapest entry first. Entry = {cost, node}.
PriorityQueue<Object[]> pq = new PriorityQueue<>(Comparator.comparingInt((Object[] e) -> (int) e[0]));
pq.add(new Object[]{0, src});
while (!pq.isEmpty()) {
Object[] top = pq.remove();
int d = (int) top[0];
String u = (String) top[1];
if (d > dist.get(u)) continue; // stale entry: a better one was found
for (var road : graph.get(u).entrySet()) {
String v = road.getKey();
int w = road.getValue();
if (d + w < dist.get(v)) { // relax the road
dist.put(v, d + w);
pq.add(new Object[]{dist.get(v), v});
}
}
}
return dist;
}
public static void main(String[] args) {
Map<String, Map<String, Integer>> graph = Map.of(
"A", Map.of("B", 4, "C", 1),
"B", Map.of("A", 4, "C", 2, "D", 1),
"C", Map.of("A", 1, "B", 2, "D", 5),
"D", Map.of("B", 1, "C", 5, "E", 3),
"E", Map.of("D", 3));
for (var e : dijkstra(graph, "A").entrySet()) System.out.println(e.getKey() + ": " + e.getValue());
}
}Go
package main
import (
"container/heap"
"fmt"
"math"
"sort"
)
// An entry in the priority queue: a node and the cost we reached it with.
type item struct {
cost int
node string
}
// minHeap pops the cheapest item first (container/heap does the heap work).
type minHeap []item
func (h minHeap) Len() int { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i].cost < h[j].cost }
func (h minHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(x any) { *h = append(*h, x.(item)) }
func (h *minHeap) Pop() any {
old := *h
last := old[len(old)-1]
*h = old[:len(old)-1]
return last
}
// dijkstra: graph is node -> {neighbour: weight}. Returns the cheapest cost to every node.
func dijkstra(graph map[string]map[string]int, src string) map[string]int {
dist := map[string]int{}
for n := range graph {
dist[n] = math.MaxInt
}
dist[src] = 0
pq := &minHeap{{0, src}}
for pq.Len() > 0 {
top := heap.Pop(pq).(item)
d, u := top.cost, top.node
if d > dist[u] {
continue // stale entry: a better one was found
}
for v, w := range graph[u] {
if d+w < dist[v] { // relax the road
dist[v] = d + w
heap.Push(pq, item{dist[v], v})
}
}
}
return dist
}
func main() {
graph := map[string]map[string]int{
"A": {"B": 4, "C": 1},
"B": {"A": 4, "C": 2, "D": 1},
"C": {"A": 1, "B": 2, "D": 5},
"D": {"B": 1, "C": 5, "E": 3},
"E": {"D": 3},
}
dist := dijkstra(graph, "A")
names := make([]string, 0, len(dist))
for n := range dist {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
fmt.Printf("%s: %d\n", n, dist[n])
}
}Time: O((V + E) log V) · Extra space: O(V). With a min-heap, each edge may push one entry and each push or pop costs a little log work.
Watch out for
- Using Dijkstra with negative edge weights. The "locked in" guarantee breaks. Use Bellman-Ford.
- Forgetting to skip stale heap entries, which repeats work and can slow things down.
- Using a plain list and scanning for the minimum every time. It works, but is O(V²).
Quick check
- Why is it safe to lock the vertex with the smallest distance?
- Because the heap is sorted
- Every other path to it must go through something at least as far, and weights are not negative
- Because it has the most edges
- What does "relaxing" an edge u → v mean?
- Deleting the edge
- Sorting the neighbours
- Checking whether going through u gives a cheaper cost to v and updating it
- Which graphs break Dijkstra?
- Graphs with negative edge weights
- Graphs with cycles
- Undirected graphs