Arcs: S→T 6, S→Y 4, Y→T 1, Y→X 9, Y→Z 4, T→X 2, Z→X 4, X→Z 5. Find the shortest distances and paths from S.
Shortest-path algorithms find minimum-weight routes in weighted graphs. Dijkstra (greedy, non-negative weights), Bellman–Ford (negative edges, detects negative cycles) and Floyd–Warshall (all pairs, dynamic programming) are the classics, with BFS for unweighted graphs.
In a weighted graph the weight of a path is the sum of its edge weights, and the shortest-path distance δ(u, v) is the minimum weight over all u-to-v paths (∞ if v is unreachable). Weights may stand for kilometres, travel time, cost or delay. ‘Shortest’ therefore means lightest, not fewest edges — those coincide only when every edge has the same weight.
| Variant | Question | Typical algorithm |
|---|---|---|
| Single-source (SSSP) | distances from one source s to every vertex | Dijkstra, Bellman–Ford, BFS (unweighted) |
| Single-pair | distance from s to one target t | run SSSP and stop early (or A* search) |
| Single-destination | distances from every vertex to t | SSSP on the graph with all edges reversed |
| All-pairs (APSP) | distance between every pair | Floyd–Warshall, or V runs of Dijkstra (Johnson's algorithm) |
Two structural facts drive the algorithms. Optimal substructure: every subpath of a shortest path is itself a shortest path, so distances can be built from smaller ones. Bounded length: if no negative-weight cycle exists, some shortest path is simple, with at most V − 1 edges. A negative edge is harmless in itself, but a negative cycle reachable from s makes distances undefined — every lap around it lowers the cost, so δ = −∞.
Unweighted graphs. If every edge has weight 1 (or any one common weight), BFS from s already computes shortest paths: it discovers vertices in increasing order of hop count, and dist[v] is set once, the first time v is reached. Cost O(V + E) — no priority queue needed. A variant, 0-1 BFS, handles weights 0 and 1 with a deque (weight-0 edges go to the front).
Directed acyclic graphs. Topologically sort the DAG, then relax the outgoing edges of each vertex in that order. When a vertex's turn comes, every path into it has already been relaxed, so its distance is final. This runs in O(V + E) and works even with negative weights, because a DAG cannot contain a cycle of any kind. (Negating all weights turns it into the longest-path algorithm used in project scheduling, the critical path method.)
Edsger W. Dijkstra devised the algorithm in 1956 and published it in 1959. It is greedy: it keeps a set of finalised vertices whose distances are known, and at each step it finalises the unfinalised vertex with the smallest tentative distance, then relaxes that vertex's outgoing edges. With non-negative weights the choice is safe: any other route to that vertex must leave the finalised set through a vertex that is at least as far away, and adding non-negative edges can only make it longer.
#include <stdio.h>
#include <limits.h>
#define V 6
#define INF INT_MAX
const char *name = "ABCDEF";
void printPath(const int parent[], int v) {
if (parent[v] != -1) { printPath(parent, parent[v]); printf("->"); }
printf("%c", name[v]);
}
void dijkstra(int g[V][V], int src) {
int dist[V], done[V], parent[V];
for (int i = 0; i < V; i++) { dist[i] = INF; done[i] = 0; parent[i] = -1; }
dist[src] = 0;
for (int round = 0; round < V; round++) {
int u = -1;
for (int i = 0; i < V; i++) /* closest unfinished vertex */
if (!done[i] && dist[i] != INF && (u == -1 || dist[i] < dist[u])) u = i;
if (u == -1) break; /* the rest are unreachable */
done[u] = 1; /* dist[u] is now final */
for (int v = 0; v < V; v++) /* relax edges leaving u */
if (g[u][v] && !done[v] && dist[u] + g[u][v] < dist[v]) {
dist[v] = dist[u] + g[u][v];
parent[v] = u;
}
}
for (int v = 0; v < V; v++) {
printf("%c: %2d ", name[v], dist[v]);
printPath(parent, v);
printf("\n");
}
}
int main(void) {
int g[V][V] = {{0}}; /* 0 = no edge */
int e[][3] = {{0,1,4}, {0,2,2}, {1,2,1}, {1,3,5}, {2,3,8},
{2,4,10}, {3,4,2}, {3,5,6}, {4,5,3}};
for (int i = 0; i < 9; i++) g[e[i][0]][e[i][1]] = g[e[i][1]][e[i][0]] = e[i][2];
dijkstra(g, 0); /* F: 13 A->C->B->D->E->F */
return 0;
}| Priority queue | Extract-min | Decrease-key | Total | Best for |
|---|---|---|---|---|
| Unsorted array (linear scan) | O(V) | O(1) | O(V²) | dense graphs (E ≈ V²) |
| Binary heap | O(log V) | O(log V) | O((V + E) log V) | sparse graphs — the usual choice |
| Fibonacci heap | O(log V) amortised | O(1) amortised | O(E + V log V) | theory; very large sparse graphs |
Undirected graph: A–B 4, A–C 2, B–C 1, B–D 5, C–D 8, C–E 10, D–E 2, D–F 6, E–F 3. Source A. Each row shows the tentative distances after the extracted vertex has relaxed its edges; ✓ marks a finalised distance.
| Step | Extract | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|
| init | — | 0 | ∞ | ∞ | ∞ | ∞ | ∞ |
| 1 | A (0) | 0 ✓ | 4 | 2 | ∞ | ∞ | ∞ |
| 2 | C (2) | 0 ✓ | 3 (via C) | 2 ✓ | 10 | 12 | ∞ |
| 3 | B (3) | 0 ✓ | 3 ✓ | 2 ✓ | 8 (via B) | 12 | ∞ |
| 4 | D (8) | 0 ✓ | 3 ✓ | 2 ✓ | 8 ✓ | 10 (via D) | 14 |
| 5 | E (10) | 0 ✓ | 3 ✓ | 2 ✓ | 8 ✓ | 10 ✓ | 13 (via E) |
| 6 | F (13) | 0 ✓ | 3 ✓ | 2 ✓ | 8 ✓ | 10 ✓ | 13 ✓ |
| Vertex | Distance | Shortest path |
|---|---|---|
| B | 3 | A → C → B (cheaper than the direct edge of weight 4) |
| C | 2 | A → C |
| D | 8 | A → C → B → D |
| E | 10 | A → C → B → D → E (not the direct C–E edge: 2 + 10 = 12) |
| F | 13 | A → C → B → D → E → F |
Failure with a negative edge. Take arcs S→A 2, S→B 5, B→A −4 and A→C 1. Dijkstra extracts A first (distance 2), then C (3), and only then B (5). Relaxing B→A would give A = 1, but A is already final, so it is never revisited: Dijkstra reports A = 2 and C = 3, while the true distances are A = 1 (S→B→A) and C = 2. The greedy assumption — ‘nothing found later can be shorter’ — fails as soon as an edge can reduce a path's cost.
The algorithm is named after Richard Bellman (1958) and Lester Ford Jr. (1956); Edward Moore published it independently in 1959. It simply relaxes every edge, V − 1 times. After pass k, d[v] is no larger than the weight of the best path to v that uses at most k edges; since a shortest path needs at most V − 1 edges, V − 1 passes suffice. One extra pass then tests for trouble: if any edge can still be relaxed, a negative cycle is reachable from the source.
#include <stdio.h>
#include <limits.h>
#define V 5
#define E 6
#define INF INT_MAX
struct Edge { int u, v, w; };
const char *name = "SABCD";
int main(void) {
struct Edge e[E] = {{3,4,2}, {1,3,3}, {2,1,-2}, {0,1,5}, {0,2,4}, {2,4,6}};
/* C->D 2, A->C 3, B->A -2, S->A 5, S->B 4, B->D 6 */
int dist[V];
for (int i = 0; i < V; i++) dist[i] = INF;
dist[0] = 0;
for (int pass = 1; pass <= V - 1; pass++) { /* V - 1 rounds */
int changed = 0;
for (int j = 0; j < E; j++)
if (dist[e[j].u] != INF && dist[e[j].u] + e[j].w < dist[e[j].v]) {
dist[e[j].v] = dist[e[j].u] + e[j].w;
changed = 1;
}
printf("after pass %d:", pass);
for (int i = 0; i < V; i++) {
if (dist[i] == INF) printf(" %c=inf", name[i]);
else printf(" %c=%d", name[i], dist[i]);
}
printf("\n");
if (!changed) break; /* early exit */
}
for (int j = 0; j < E; j++) /* the extra check pass */
if (dist[e[j].u] != INF && dist[e[j].u] + e[j].w < dist[e[j].v]) {
printf("negative cycle reachable from S\n");
return 1;
}
printf("no negative cycle\n");
return 0;
}| After pass | S | A | B | C | D | What changed |
|---|---|---|---|---|---|---|
| 0 (start) | 0 | ∞ | ∞ | ∞ | ∞ | — |
| 1 | 0 | 5 | 4 | ∞ | 10 | S→A, S→B, then B→D |
| 2 | 0 | 2 | 4 | 8 | 10 | A→C (5 + 3), then B→A (4 − 2) |
| 3 | 0 | 2 | 4 | 5 | 10 | A→C again (2 + 3) |
| 4 | 0 | 2 | 4 | 5 | 7 | C→D (5 + 2) |
| check | no edge improves — no negative cycle |
Final distances: A = 2 (S→B→A), B = 4, C = 5 (S→B→A→C), D = 7 (…→C→D). Because the arcs were listed ‘backwards’, the improvements crept forward one edge per pass and all V − 1 = 4 passes were needed. Listing the same arcs as S→A, S→B, B→A, A→C, C→D, B→D finishes in one pass (and a second, unchanged pass stops the loop) — the order of the edge list affects speed, never correctness. Bellman–Ford is the basis of distance-vector routing (RIP).
Robert Floyd published this all-pairs algorithm in 1962, building on Stephen Warshall's 1962 transitive-closure algorithm (Bernard Roy had found it in 1959). Number the vertices 1 … V and let dᵏ[i][j] be the weight of the shortest i-to-j path whose intermediate vertices all come from {1, …, k}. Allowing one more vertex, k, either does not help, or the best path passes through k exactly once:
Worked example: arcs 1→2 (5), 1→4 (2), 2→3 (4), 3→1 (3), 4→2 (1), 4→3 (7). Each matrix row below lists d[i][1], d[i][2], d[i][3], d[i][4].
| Matrix | Row 1 | Row 2 | Row 3 | Row 4 | Updates made in this round |
|---|---|---|---|---|---|
| D⁰ | 0 5 ∞ 2 | ∞ 0 4 ∞ | 3 ∞ 0 ∞ | ∞ 1 7 0 | the edge weights |
| D¹ (via 1) | 0 5 ∞ 2 | ∞ 0 4 ∞ | 3 8 0 5 | ∞ 1 7 0 | d32 = 3 + 5 = 8, d34 = 3 + 2 = 5 |
| D² (via 2) | 0 5 9 2 | ∞ 0 4 ∞ | 3 8 0 5 | ∞ 1 5 0 | d13 = 5 + 4 = 9, d43 = 1 + 4 = 5 |
| D³ (via 3) | 0 5 9 2 | 7 0 4 9 | 3 8 0 5 | 8 1 5 0 | d21 = 4 + 3 = 7, d24 = 4 + 5 = 9, d41 = 5 + 3 = 8 |
| D⁴ (via 4) | 0 3 7 2 | 7 0 4 9 | 3 6 0 5 | 8 1 5 0 | d12 = 2 + 1 = 3, d13 = 2 + 5 = 7, d32 = 5 + 1 = 6 |
#include <stdio.h>
#define V 4
#define INF 9999
int main(void) {
int d[V][V] = { {0, 5, INF, 2 },
{INF, 0, 4, INF},
{3, INF, 0, INF},
{INF, 1, 7, 0 } };
for (int k = 0; k < V; k++) /* intermediate vertex: outermost */
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
if (d[i][k] + d[k][j] < d[i][j])
d[i][j] = d[i][k] + d[k][j];
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) printf("%3d", d[i][j]);
printf("\n"); /* 0 3 7 2 / 7 0 4 9 / 3 6 0 5 / 8 1 5 0 */
}
return 0;
}Reading the result: the cheapest route from 1 to 3 costs 7 along 1 → 4 → 2 → 3, beating both the arc 1 → 2 → 3 (9) and 1 → 4 → 3 (9). To recover the routes themselves, keep a ‘next hop’ matrix updated whenever an entry improves. Warshall's transitive closure is the same triple loop on a Boolean matrix: t[i][j] = t[i][j] ∨ (t[i][k] ∧ t[k][j]) tells whether j is reachable from i at all.
| Algorithm | Problem | Negative edges? | Detects negative cycles? | Technique | Time |
|---|---|---|---|---|---|
| BFS | single source, unweighted | — | — | queue | O(V + E) |
| DAG relaxation | single source on a DAG | yes | — (no cycles exist) | topological order | O(V + E) |
| Dijkstra | single source, weights ≥ 0 | no | no | greedy + priority queue | O(V²) or O((V + E) log V) |
| Bellman–Ford | single source | yes | yes | repeated relaxation (DP) | O(VE) |
| Floyd–Warshall | all pairs | yes | yes (d[i][i] < 0) | dynamic programming | O(V³) |
| Johnson | all pairs, sparse graphs | yes | yes | Bellman–Ford reweighting + V × Dijkstra | O(VE log V) |
A*.Try the problem first, then reveal the working one step at a time.
Arcs: S→T 6, S→Y 4, Y→T 1, Y→X 9, Y→Z 4, T→X 2, Z→X 4, X→Z 5. Find the shortest distances and paths from S.
Add the arc C→B with weight −4 to the Bellman–Ford example (same edge order, new arc last). Run the algorithm.
Three vertices with arcs 1→2 (5), 1→3 (6), 2→3 (−2), 3→1 (4). Compute all-pairs shortest distances.
Run Dijkstra on the worked-table graph (A–B 4, A–C 2, B–C 1, B–D 5, C–D 8, C–E 10, D–E 2, D–F 6, E–F 3), this time from source D. Give the final distances and paths.
A graph has V = 100 vertices and E = 1000 edges. How many edge relaxations does Bellman–Ford perform in the worst case? Estimate Dijkstra's cost with a binary heap for comparison.
Run Floyd–Warshall on arcs 1→2 (8), 1→4 (1), 2→3 (1), 3→1 (4), 4→2 (2), 4→3 (9). Give D¹ and the final matrix.
To use Dijkstra on a graph with a negative edge, a student adds a constant c to every weight. Arcs: S→A 2, A→T −1, S→T 2. Show that the shortest S-to-T path changes when c = 2.
In what order should the arcs of the Bellman–Ford example (S→A 5, S→B 4, B→A −2, A→C 3, C→D 2, B→D 6) be listed so that a single pass finds every distance? Why can't Bellman–Ford rely on that in general?
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.