Skip to content
Definition
Dijkstra's Algorithm finds the shortest path between nodes in a weighted graph. It maintains a set of nodes whose shortest distance from the source is known.

How Dijkstra's Algorithm Works

pseudocode
procedure dijkstra(graph, source):
    // Initialise distances
    for each vertex v in graph:
        distance[v] = INFINITY
        visited[v] = False
    end for
    distance[source] = 0
    
    while there are unvisited vertices:
        // Pick unvisited vertex with smallest distance
        current = vertex with minimum distance where visited[current] == False
        visited[current] = True
        
        // Update distances to neighbours
        for each neighbour of current:
            if not visited[neighbour] then
                newDist = distance[current] + weight(current, neighbour)
                if newDist < distance[neighbour] then
                    distance[neighbour] = newDist
                end if
            end if
        end for
    end while
    
    return distance
end procedure
Key Point
Dijkstra aspectNotes
TypeGreedy algorithm
PurposeShortest path from source in weighted graph
RequirementNon-negative edge weights
OutputShortest known distance to each reachable vertex
Core stepAction
1Initialise source distance = 0, others = ∞
2Pick unvisited node with smallest tentative distance
3Relax/update neighbour distances
4Mark node visited
5Repeat until all reachable nodes processed

Worked Example: Tracing Dijkstra's Algorithm

Find the shortest path from A to F in a graph that has these edges.

EdgeA–BA–CB–DC–DC–ED–FE–F
Weight3462547
Worked Example
Working: the unvisited node with the smallest distance is visited next
Node visitedDistance from AUpdates to its unvisited neighbours
A0B = 3 (from A); C = 4 (from A)
B3D = 3 + 6 = 9 (from B)
C4D = 4 + 2 = 6, which is less than 9, so D becomes 6 (from C); E = 4 + 5 = 9 (from C)
D6F = 6 + 4 = 10 (from D)
E9F through E would be 9 + 7 = 16, which is not less than 10, so F is unchanged
F10End node reached
Final table
NodeDistance from APrevious node
A0None
B3A
C4A
D9, then 6B, then C
E9C
F10D
The path is read backwards from the end node using the previous-node column: F was reached from D, D from C and C from A.

Shortest path: A, C, D, F. Distance: 10.
Exam Tip
Show every distance a node has held, not only the last one, so that it is clear when a shorter route replaced a longer one (D: 9, then 6). Finish by stating both the path and its total distance.