Weighted shortest paths
When links take different amounts of time, the route with the fewest links may take longer. Dijkstra’s algorithm repeatedly settles the nearest unfinished vertex.
Simple example
A direct trip costs 8. Going through C costs 2 plus 3. Find and print the lowest total, 5.
const std = @import("std");
fn show(value: i64) !void {
var buffer: [64]u8 = undefined;
var writer = std.fs.File.stdout().writer(&buffer);
try writer.interface.print("{d}\n", .{value});
try writer.interface.flush();
}
pub fn main() !void {
const offsets = [_]i64{0, 2, 2, 3};
const edges = [_]i64{1, 2, 1};
const minutes = [_]i64{8, 2, 3};
var distance = [_]i64{0, -1, -1};
var settled = [_]i64{0, 0, 0};
while (true) {
var best: i64 = -1;
var i: i64 = 0;
while (i < 3) {
if ((settled[@intCast(i)] == 0 and distance[@intCast(i)] >= 0)) {
if ((best == -1 or distance[@intCast(i)] < distance[@intCast(best)])) {
best = i;
}
}
i += 1;
}
if (best == -1) {
break;
}
settled[@intCast(best)] = 1;
i = offsets[@intCast(best)];
while (i < offsets[@intCast((best + 1))]) {
const other: i64 = edges[@intCast(i)];
const cost: i64 = (distance[@intCast(best)] + minutes[@intCast(i)]);
if ((distance[@intCast(other)] == -1 or cost < distance[@intCast(other)])) {
distance[@intCast(other)] = cost;
}
i += 1;
}
}
try show(distance[1]);
}
5
Everyday examples
Choose the fastest bus trip
A direct ride takes 12 minutes. A connection takes 4 minutes then 5, with no extra wait. Which total is smaller?
Add the travel times for each route. The two-leg trip takes 9 minutes, which is less than 12.
Update a delivery estimate
The first road found to a shop costs 10 minutes. Later you reach a junction in 3 minutes and see a 4-minute road to the shop. What estimate replaces 10?
The new route costs 7. Update the estimate and remember the junction if you need to reconstruct the path.
Handle a closed connection
Only A and B are connected. A map query asks for the travel time from A to C. What result is appropriate?
C has no reachable route. Report it as unreachable rather than giving it a time of zero.
Cost and limits
Dijkstra’s algorithm requires nonnegative edge weights. This tiny example scans the unfinished vertices. With a binary heap and neighbour lists, the usual running time is O((V + E) log V).