TExcelTAD
Home › Data Structures & Algorithms › Dijkstra's Algorithm

Dijkstra's Algorithm

Dijkstra's algorithm (Edsger Dijkstra, 1956) finds the shortest paths from one start vertex to every other vertex in a graph with non-negative edge weights. It is the workhorse behind route planners and network routing.

The idea

Dijkstra grows a set of finished vertices whose shortest distance is known for sure:

  1. Set dist[start] = 0 and every other distance to infinity.
  2. Pick the unfinished vertex with the smallest distance, u, and mark it finished.
  3. Relax every edge from u to an unfinished neighbour v: if dist[u] + w < dist[v], update dist[v].
  4. Repeat from step 2 until every reachable vertex is finished.

Why is the closest unfinished vertex safe to finish? Any other route to it would have to leave the finished set through some other unfinished vertex that is already at least as far away, and with non-negative weights the rest of that route can only add to the cost.

The numbers next to the vertices are their current dist values. Watch B: first reached directly with distance 4, it improves to 3 once C (distance 2) is finished, because 2 + 1 < 4.

Implementation with a priority queue

Finding the closest unfinished vertex by scanning all of them costs O(V) per step. A min-heap (Python's heapq) hands it over in O(log V). We push (distance, vertex) pairs; when a vertex's distance improves we simply push it again and skip outdated entries when they come out.

python · try it yourself
import heapq

graph = {
    "A": {"B": 4, "C": 2},
    "B": {"A": 4, "C": 1, "D": 5},
    "C": {"A": 2, "B": 1, "D": 8, "E": 10},
    "D": {"B": 5, "C": 8, "E": 2, "F": 6},
    "E": {"C": 10, "D": 2, "F": 2},
    "F": {"D": 6, "E": 2},
}

def dijkstra(graph, start):
    dist = {v: float("inf") for v in graph}
    prev = {v: None for v in graph}
    dist[start] = 0
    heap = [(0, start)]
    done = set()
    while heap:
        d, u = heapq.heappop(heap)
        if u in done:
            continue                      # an outdated entry
        done.add(u)
        print(f"finish {u} at distance {d}")
        for v in sorted(graph[u]):
            if v in done:
                continue
            nd = d + graph[u][v]
            if nd < dist[v]:
                dist[v], prev[v] = nd, u
                heapq.heappush(heap, (nd, v))
    return dist, prev

dist, prev = dijkstra(graph, "A")
print(dist)
finish A at distance 0
finish C at distance 2
finish B at distance 3
finish D at distance 8
finish E at distance 10
finish F at distance 12
{'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 12}

The vertices are finished in the same order as in the animation, and the final distances match its last frame: A=0, B=3, C=2, D=8, E=10, F=12.

Getting the routes

The prev table records each vertex's predecessor on its shortest path. Walking it backwards rebuilds the routes:

python · try it yourself
import heapq

graph = {
    "A": {"B": 4, "C": 2}, "B": {"A": 4, "C": 1, "D": 5},
    "C": {"A": 2, "B": 1, "D": 8, "E": 10}, "D": {"B": 5, "C": 8, "E": 2, "F": 6},
    "E": {"C": 10, "D": 2, "F": 2}, "F": {"D": 6, "E": 2},
}

def dijkstra(graph, start):
    dist = {v: float("inf") for v in graph}
    prev = {v: None for v in graph}
    dist[start] = 0
    heap = [(0, start)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue
        for v, w in graph[u].items():
            if d + w < dist[v]:
                dist[v], prev[v] = d + w, u
                heapq.heappush(heap, (d + w, v))
    return dist, prev

def route(prev, target):
    path = []
    while target is not None:
        path.append(target)
        target = prev[target]
    return " -> ".join(reversed(path))

dist, prev = dijkstra(graph, "A")
for v in "BDF":
    print(f"{v}: {dist[v]:>2} via {route(prev, v)}")
B:  3 via A -> C -> B
D:  8 via A -> C -> B -> D
F: 12 via A -> C -> B -> D -> E -> F

The path to F goes A → C → B → D → E → F: five edges, yet cheaper (12) than A → B → D → F (15).

Why negative weights break it

Dijkstra never revisits a finished vertex. With a negative edge, a finished vertex could later become cheaper to reach, and the algorithm would not notice:

python · try it yourself
import heapq

graph = {"S": {"A": 2, "B": 5}, "A": {}, "B": {"A": -4}}

def dijkstra(graph, start):
    dist = {v: float("inf") for v in graph}
    dist[start] = 0
    heap, done = [(0, start)], set()
    while heap:
        d, u = heapq.heappop(heap)
        if u in done:
            continue
        done.add(u)
        for v, w in graph[u].items():
            if v not in done and d + w < dist[v]:
                dist[v] = d + w
                heapq.heappush(heap, (d + w, v))
    return dist

print(dijkstra(graph, "S"))
print("true shortest distance to A: S -> B -> A =", 5 + -4)
{'S': 0, 'A': 2, 'B': 5}
true shortest distance to A: S -> B -> A = 1

A was finished with distance 2 before the cheaper route through B (5 - 4 = 1) was seen. For graphs with negative weights, use Bellman-Ford.

Complexity

Implementation Time Good for
Array scan for the minimum O(V²) dense graphs
Binary heap (heapq) O((V + E) log V) sparse graphs (most real ones)

Tip: To find the route to one target only, stop as soon as the target is finished. Route planners also use A*, which adds an estimate of the remaining distance to the priority so that the search heads towards the target.

Test yourself

Which vertex does Dijkstra's algorithm finish next?

  1. The one added most recently
  2. The unfinished vertex with the smallest tentative distance
  3. The one with the most edges
  4. Vertices in alphabetical order

In the lesson's graph, why does B's distance change from 4 to 3?

  1. The edge A-B gets cheaper
  2. Finishing C (distance 2) and relaxing C-B (weight 1) gives 3
  3. B is visited twice
  4. A rounding error

Dijkstra's algorithm is not correct when the graph has...

  1. cycles
  2. negative edge weights
  3. more than 100 vertices
  4. undirected edges