Dijkstra's Algorithm
Computational Mathematics
Important Notice
Contents
Finding the Shortest Path
Imagine you need to travel from Dublin to Cork. There are many possible routes — some faster, some shorter, some cheaper on fuel. This is a path finding problem: given a network of locations connected by roads, find the "best" route from one point to another. "Best" could mean least time, least distance, most bandwidth, or least cost — these are all optimisation problems.
We can model these networks as weighted graphs: locations become nodes (also called vertices), roads become edges, and each edge has a weight — a number representing its cost (distance, time, etc.). An algorithm is simply a step-by-step series of instructions to solve a problem. Dijkstra's Algorithm (pronounced "Dike-stra", after Dutch computer scientist Edsger Dijkstra) is one of the most famous algorithms for finding the shortest path in a weighted graph.
The objective is simple: find one sequence of nodes connecting a start node to an end node that has the least combined edge weight. Dijkstra's approach works by exploring outward from the start node, always picking the closest unvisited neighbour first, and gradually building up a table of shortest known distances. By the time it reaches the destination, it guarantees the path is optimal.
Why Do We Need an Algorithm?
The brute-force approach does not scale
Try every possible path from A to H, calculate each total cost, pick the shortest.
| 7 nodes | Hundreds of paths |
| 100 nodes | Millions of paths |
| 1,000 nodes | More paths than atoms in the universe |
Visit nodes smartly — always pick the closest unvisited node next. Each node is visited at most once.
| 7 nodes | 7 steps |
| 100 nodes | ~100 steps |
| 1,000 nodes | ~1,000 steps |
Weighted Graph
The graph we'll use to trace Dijkstra's algorithm
Each number on an edge represents the cost of travelling between two nodes
The Algorithm
Four steps to find the shortest path
Step 0 — Start at Node A
Initialise distances and begin
Step 1 — Visit Node C (cost 1)
C has the smallest distance in the queue
Step 2 — Visit Node B (cost 2)
B has the smallest distance among unvisited nodes
Step 3 — Visit Node D (cost 3)
D's neighbours are already visited — no updates
Steps 4 & 5 — Visit E (cost 5), then F (cost 7)
Getting closer to H
Result — Shortest Path Found!
A → C → F → H with total cost 9
Worked Example 2 — A Larger Graph
Finding the shortest path from S to T in a 7-node graph
Worked Example 2 — Animated Walkthrough
Watch Dijkstra find the path from S to T
Worked Example 2 — Column Walkthrough
Step-by-step columns for S to T
Worked Example 3 — Finding All Shortest Paths
Sometimes the journey matters more than the destination
Worked Example 3 — Full Dijkstra Run
Finding shortest paths from P to all nodes
| Destination | Shortest Distance | Path |
|---|---|---|
| Q | 1 | P → Q |
| R | 3 | P → Q → R |
| S | 6 | P → Q → R → S |
| T | 8 | P → Q → R → T |
| U | 7 | P → Q → R → S → U |
Worked Example 3 — Column Walkthrough
Step-by-step columns for P to all nodes
Step-by-Step Walkthrough
Running Dijkstra from A to H — following the algorithm
Dijkstra vs A* — Grid Comparison
Same map, same cost — but look at how many nodes each algorithm visits

A* visited 90 nodes. Dijkstra visited 555 — over 6 times more. Video by Kevin Wang.
A* visited 90 nodes. Dijkstra visited 555 — over 6 times more. Video by Kevin Wang.
Dijkstra vs A* — Real-World Comparison
Watch Dijkstra explore every street in Rome before finding the path

Dijkstra took 21:04 to find the path. A* found the same path in just 02:03. Video by Anthony Madorsky.
Dijkstra took 21:04 to find the path. A* found the same path in just 02:03. Video by Anthony Madorsky.
Dijkstra vs A* — Understanding the Difference
Two algorithms, one goal — but very different strategies
- •Explores nodes in ALL directions equally
- •Guaranteed to find the shortest path
- •No knowledge of where the target is
- •Like a ripple spreading in a pond
- •Visits many unnecessary nodes
- •Explores towards the target first
- •Also guaranteed shortest path (with admissible heuristic)
- •Uses a heuristic — estimated distance to target
- •Like following a compass towards your destination
- •Visits far fewer nodes
A* adds one extra piece of information: an estimate of how far each node is from the target. Instead of picking the node with the smallest distance from start (like Dijkstra), A* picks the node with the smallest distance from start + estimated distance to target. This simple addition dramatically reduces the number of nodes explored.
| Feature | Dijkstra | A* |
|---|---|---|
| Uses heuristic? | No | Yes |
| Finds shortest path? | Always | Yes (with admissible heuristic) |
| Speed | Slower (explores everything) | Faster (focused search) |
| Memory usage | Higher | Lower |
| Best for | All shortest paths from one source | Single source to single target |
| Used in | Network routing, database queries | GPS navigation, video games |
Real-World Applications
Where shortest path algorithms power our daily lives
Every time you ask Google Maps or Apple Maps for directions, a variant of Dijkstra’s algorithm runs on millions of road segments. The edges are roads, weights are travel times (updated in real-time with traffic data), and the algorithm finds the fastest route. Modern GPS uses A* with geographical distance as the heuristic.
When you send a message on WhatsApp, it travels through multiple routers to reach its destination. Protocols like OSPF (Open Shortest Path First) use Dijkstra’s algorithm to find the fastest path through the network. Each router is a node, each connection is an edge weighted by latency or bandwidth.
In games like Age of Empires, Civilization, or any strategy game, units need to navigate around obstacles to reach their destination. A* is the standard pathfinding algorithm in game development. It runs thousands of times per second to move characters, enemies, and NPCs around the map.
LinkedIn’s ‘degrees of connection’ and Facebook’s ‘People You May Know’ use graph algorithms to find short paths between users. The ‘six degrees of separation’ concept is essentially a shortest path problem on a social graph with billions of nodes.
Dijkstra's Algorithm in Java
Using a priority queue to find the shortest path
import java.util.*; public class DijkstraAlgorithm { // Find shortest distances from start to all nodes public static int[] dijkstra(int[][] graph, int start) { int n = graph.length; int[] distances = new int[n]; boolean[] visited = new boolean[n]; // Initialise all distances to "infinity" Arrays.fill(distances, Integer.MAX_VALUE); distances[start] = 0; // Priority queue: {distance, node} PriorityQueue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); queue.offer(new int[]{0, start}); while (!queue.isEmpty()) { int[] current = queue.poll(); int dist = current[0], node = current[1]; if (visited[node]) continue; visited[node] = true; // Check all neighbours for (int next = 0; next < n; next++) { if (graph[node][next] > 0 && !visited[next]) { int newDist = dist + graph[node][next]; if (newDist < distances[next]) { distances[next] = newDist; queue.offer(new int[]{newDist, next}); } } } } return distances; } }
public class Main { public static void main(String[] args) { // Adjacency matrix — 0 means no direct connection // A B C D E F H int[][] graph = { {0, 2, 1, 0, 0, 0, 0}, // A {2, 0, 0, 1, 3, 0, 0}, // B {1, 0, 0, 3, 0, 6, 0}, // C {0, 1, 3, 0, 0, 0, 0}, // D {0, 3, 0, 0, 0, 5, 0}, // E {0, 0, 6, 0, 5, 0, 2}, // F {0, 0, 0, 0, 0, 2, 0} // H }; String[] nodes = {"A","B","C","D","E","F","H"}; int[] distances = DijkstraAlgorithm.dijkstra(graph, 0); // Print shortest distances from A for (int i = 0; i < nodes.length; i++) { System.out.println("A → " + nodes[i] + " = " + distances[i]); } // Output: A → H = 9 } }
Quick Reference
| Concept | Notation | Meaning |
|---|---|---|
| Node (Vertex) | A, B, C... | A point/location in the graph |
| Edge | A—B | A connection between two nodes |
| Weight | w(A,B) = 3 | The cost of travelling along an edge |
| Weighted Graph | G(V, E) | A graph where each edge has a weight |
| Adjacency Matrix | M[i][j] | A table storing edge weights between all node pairs |
| Distance Table | d[v] | Tracks the shortest known distance to each node |
| Shortest Path | A → C → F → H | The sequence of nodes with least total weight |
| Priority Queue | min-heap | Picks the unvisited node with smallest distance |
Practice Exercises
Test your understanding of Dijkstra’s Algorithm
What is the total cost?
Show the distance table after each step and identify the shortest path.
Find the shortest path from A to E. Show your working at each step.
a) Run Dijkstra from W to find the shortest distance to every store.
b) What is the shortest path from W to S3?
c) If the road W–S2 is closed for construction, what is the new shortest path from W to S3?
int[][] graph = {
{0, 6, 0, 1, 0},
{6, 0, 5, 2, 2},
{0, 5, 0, 0, 5},
{1, 2, 0, 0, 1},
{0, 2, 5, 1, 0}
};a) What does Dijkstra report as shortest distance A to C?
b) What is the ACTUAL shortest distance?
c) Why does Dijkstra fail?
d) Name an algorithm that handles negative weights.
Show your working step by step.
Show every step of the algorithm and identify the shortest path.
Edges: S–A(2), S–B(5), A–C(4), A–E(7), B–D(2), B–E(1), C–T(3), D–T(4), E–C(1), E–D(3). Show your complete working.
Edges: R1–R2(3), R1–R3(6), R2–R4(2), R2–R5(5), R3–R5(3), R3–R6(1), R4–R7(4), R5–R7(2), R5–R6(2), R6–R8(5), R7–R8(1). Show the full distance table at each step.
Answers
| A | B | C | |
|---|---|---|---|
| A | 0 | 3 | 5 |
| B | 3 | 0 | 1 |
| C | 5 | 1 | 0 |
Part a) Dijkstra from W:
| Step | Current | W | S1 | S2 | S3 | S4 |
|---|---|---|---|---|---|---|
| 0 | W | 0 | 10 | 5 | ∞ | ∞ |
| 1 | S2 | 0 | 8 | 5 | 13 | 7 |
| 2 | S4 | 0 | 8 | 5 | 11 | 7 |
| 3 | S1 | 0 | 8 | 5 | 9 | 7 |
| 4 | S3 | 0 | 8 | 5 | 9 | 7 |
Shortest distances: S1=8, S2=5, S3=9, S4=7
Part b) Shortest path W to S3:
W → S2 → S1 → S3, cost = 5 + 3 + 1 = 9
Part c) W–S2 closed:
Without the W–S2 edge, the only path to S1 is direct (cost 10). Then S1→S3 = 1. So W → S1 → S3, cost = 10 + 1 = 11.
| Step | Current | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 6 | ∞ | 1 | ∞ |
| 1 | 3 | 0 | 3 | ∞ | 1 | 2 |
| 2 | 4 | 0 | 3 | 7 | 1 | 2 |
Shortest path: 0 → 3 → 4, cost = 2 (1 + 1). The matrix shows node 0 to node 3 has weight 1, and node 3 to node 4 has weight 1.
b) The actual shortest path is A→B→C = 5 + (−10) = −5.
c) Dijkstra fails because it finalises C at distance 2 before discovering the cheaper path through B. Once a node is marked as visited, it is never reconsidered — the greedy assumption ("smallest distance is final") breaks when negative weights exist, because adding a negative weight can make a longer path shorter.
d) The Bellman-Ford algorithm handles negative weights by relaxing ALL edges V−1 times, guaranteeing all shortest paths are found.
b) Actual shortest: A→B→C = 1 + (−5) = −4.
c) Dijkstra marks C as visited at distance 4 before discovering the path through B. Once visited, nodes are never reconsidered — this is the fundamental assumption that breaks with negative weights.
d) The Bellman-Ford algorithm handles negative weights by relaxing all edges V−1 times, guaranteeing all shortest paths are found.
References
Sources used to build this material
Happy studying!
Algorithms are the foundation of efficient problem-solving in computing