Skip to content

Dijkstra's Algorithm ​

Dijkstra's algorithm finds the shortest distance from one starting vertex to every other vertex.

At a Glance ​

It records the shortest path from a specific vertex to every other vertex. It is used on graphs where each edge has a different distance (cost). If the shortest path only counts the number of edges, BFS is enough.

As an analogy, it is like working out the distance from your house to each shop on a neighborhood map. Among the shops not yet finalized, you take the one with the shortest distance found so far and finalize it as "this distance is the shortest to here." Then you check whether going through that shop gets you to other shops faster, and you update the distance table. You repeat this until every shop is finalized.

The original source introduces Dijkstra as "a shortest-path search algorithm that uses DP." This is because it resembles dynamic programming: a place whose shortest distance has been found (finalized) never needs to be computed again, and the shortest distance to the next vertex is built from shortest distances already found. Textbooks, however, usually classify it as a greedy algorithm, because at each step it picks "the vertex that is currently closest" and finalizes it right away.

To implement Dijkstra, you store two things.

What to storeExample nameMeaning
Shortest distancedistance[i]The shortest distance found so far from the start vertex to i
Visited flagvisited[i]Whether the shortest distance to i has been finalized

How It Works ​

  1. Initialize the shortest distance of every vertex to infinity.
  2. The shortest distance of the start vertex is 0. Mark the start vertex as visited.
  3. Update the shortest distances of the vertices connected to the start vertex with their edge distances.
  4. Among unvisited vertices, find the one with the smallest shortest distance. (If there is no such vertex, i.e. the remaining vertices are unreachable, stop.)
  5. Mark the found vertex as visited, then for each unvisited vertex connected to it, update the shortest distance if "the distance going through that vertex" is shorter.
  6. Repeat steps 4-5 until every vertex has been visited.

Example graph (undirected, start vertex 1)

Edge1-21-31-62-32-43-43-64-55-6
Distance7914101511269
StepVertex marked visiteddistance [1, 2, 3, 4, 5, 6]Explanation
1~31[0, 7, 9, ∞, ∞, 14]Record edge distances for 1's neighbors 2, 3 and 6
4~52 (distance 7)[0, 7, 9, 22, ∞, 14]Through 2, vertex 4 is 7+15=22. For 3, 7+10=17 > 9, so it stays
4~53 (distance 9)[0, 7, 9, 20, ∞, 11]Through 3, vertex 4 is 9+11=20 < 22 and vertex 6 is 9+2=11 < 14, so both are updated
4~56 (distance 11)[0, 7, 9, 20, 20, 11]Through 6, vertex 5 is 11+9=20
4~54 (distance 20)[0, 7, 9, 20, 20, 11]Through 4, vertex 5 is 20+6=26 > 20, so it stays
4~55 (distance 20)[0, 7, 9, 20, 20, 11]All vertices visited

Going directly from 1 to 6 costs 14, but taking the detour 1 → 3 → 6 costs 9+2=11, which is shorter. Finding and fixing these "cases where going through another vertex is shorter" is step 5 (the update).

In Pictures ​

Dijkstra in action

Image source: Wikimedia Commons

Python Code ​

Adjacency Matrix Version ​

This version translates the original source's step-by-step code directly into Python. graph[a][b] holds the edge distance between a and b, and is left as None if there is no edge.

python
INF = float("inf")


def dijkstra_matrix(graph, start):
    """Dijkstra implemented with an adjacency matrix. Vertices are numbered from 1"""
    n = len(graph) - 1
    distance = [INF] * (n + 1)              # 1. Set every shortest distance to infinity
    visited = [False] * (n + 1)

    distance[start] = 0                     # 2. Start vertex is 0, mark it visited
    visited[start] = True

    for i in range(1, n + 1):               # 3. Fill in distances of the start vertex's neighbors
        if not visited[i] and graph[start][i] is not None:
            distance[i] = graph[start][i]

    for _ in range(n - 1):
        min_dist, midx = INF, -1            # 4. Find the closest unvisited vertex
        for i in range(1, n + 1):
            if not visited[i] and distance[i] < min_dist:
                min_dist, midx = distance[i], i
        if midx == -1:                      #    Stop if no more vertices are reachable
            break

        visited[midx] = True                # 5. Finalize it and update paths that go through it
        for i in range(1, n + 1):
            if not visited[i] and graph[midx][i] is not None:
                if distance[i] > distance[midx] + graph[midx][i]:
                    distance[i] = distance[midx] + graph[midx][i]

    return distance                         # 6. Result after repeating 4~5 n-1 times


edges = [(1, 2, 7), (1, 3, 9), (1, 6, 14), (2, 3, 10), (2, 4, 15),
         (3, 4, 11), (3, 6, 2), (4, 5, 6), (5, 6, 9)]
n = 6
graph = [[None] * (n + 1) for _ in range(n + 1)]
for a, b, w in edges:
    graph[a][b] = graph[b][a] = w           # Undirected graph

print(dijkstra_matrix(graph, 1)[1:])        # Output: [0, 7, 9, 20, 20, 11]
  1. Unknown distances are set to infinity (float("inf")). Since it is larger than any real distance, it gets replaced on the first comparison.
  2. The distance to the starting point is obviously 0, and it is finalized from the start.
  3. For vertices directly connected to the starting point, the edge distance is the distance found so far.
  4. Pick the unfinalized vertex with the smallest distance. If all remaining vertices are infinity (unreachable), midx stays at -1, so we stop.
  5. Finalize the chosen vertex and update each neighbor whose distance through that vertex (distance[midx] + edge) is shorter than its current value.
  6. It finishes after finalizing the n-1 vertices other than the start one by one. A vertex that stays at infinity to the end is unreachable from the starting point.

Priority Queue (Heap) Version ​

Scanning every vertex in step 4 to find "the closest vertex" each time is slow. If you put (distance, vertex) into a min heap (Python heapq), you can pop the closest vertex in O(log V). The graph is stored as an adjacency list (adj[v] = [(neighbor, distance), ...]).

python
import heapq

INF = float("inf")


def dijkstra_heap(adj, start):
    """Dijkstra implemented with an adjacency list + min heap"""
    distance = [INF] * len(adj)
    distance[start] = 0
    pq = [(0, start)]                       # 1. Put (distance, vertex) into the min heap

    while pq:
        dist, v = heapq.heappop(pq)         # 2. Pop the closest vertex so far
        if dist > distance[v]:              # 3. Skip stale records already finalized with a shorter distance
            continue
        for nxt, w in adj[v]:               # 4. Update neighbor distances, push to the heap if reduced
            nd = dist + w
            if nd < distance[nxt]:
                distance[nxt] = nd
                heapq.heappush(pq, (nd, nxt))

    return distance


adj = [[] for _ in range(n + 1)]
for a, b, w in edges:
    adj[a].append((b, w))
    adj[b].append((a, w))

print(dijkstra_heap(adj, 1)[1:])            # Output: [0, 7, 9, 20, 20, 11]
  1. A heap is a structure that quickly gives you the smallest of the values put into it. Tuples are compared by their first value (distance), so the vertex with the shortest distance comes out first.
  2. The popped vertex is "the closest unvisited vertex." The heap replaces step 4 of the adjacency matrix version.
  3. The same vertex can enter the heap several times, once each time its distance decreases. If the popped distance is larger than the recorded shortest distance, it is a stale record and is discarded. This plays the role of visited.
  4. Only actually connected neighbors are checked, and a neighbor is updated and pushed to the heap only when its distance gets shorter.

Time and Space Complexity ​

V is the number of vertices and E is the number of edges.

ImplementationTime complexityReason
Adjacency matrix + linear searchO(V²)Each time one of the V vertices is finalized, it scans V vertices for the minimum and checks V neighbors
Adjacency list + priority queue (heap)O((V + E) log V)Each edge causes at most one heap push/pop, each costing O(log V)
  • Space complexity: distance and visited arrays take O(V). Storing the graph takes O(V²) for an adjacency matrix and O(V + E) for an adjacency list. In the heap version, up to O(E) entries can pile up in the heap.
  • On graphs with few edges (most problems), the heap version is much faster. Conversely, on a dense graph where almost every pair of vertices is connected (E ≈ V²), the adjacency matrix version may be better. For complexity notation, see the time complexity article.

Things to Know When Applying Dijkstra ​

  • Implemented with an adjacency matrix, the time complexity is O(V²).
  • Implemented with an adjacency list and a priority queue (heap), it is O((V + E) log V). Problems where linear search times out should be approached this way.
  • It can be used only when edge distances are non-negative (0 or more). A finalized vertex is never revisited, but with negative edges a "detour" found later could be shorter, making the finalized value wrong. With negative edges, use a different algorithm such as Bellman-Ford.
  • If "no edge" is marked as 0 in an adjacency matrix, it cannot be told apart from an edge of distance 0. Marking it with None (or infinity), as in the code above, is safer.

Summary ​

ConceptPlain-language summary
DijkstraFinalize the closest of the unfinalized places first, then fix the distance table using paths that go through it
Update (relaxation)When you think "going through here is shorter," lower the number in the distance table
Priority queueA tool that hands you the closest place right away without scanning everything each time
ConstraintCannot be used if any road has a negative distance

Reference: Wikipedia (Korean) - Dijkstra's algorithm, bumbums.tistory.com/4