Courses / DSA Patterns for Working Engineers / Chapter 36
Module 11 · Graph algorithms · Chapter 36 of 39
Weighted Shortest Paths: Dijkstra, Bellman-Ford and 0-1 BFS
Builds on Heaps and Two Heaps: Running Medians and Priority Scheduling, Graphs: Modelling, Breadth-First and Depth-First Search and Grids as Graphs: Flood Fill, Islands and Spreading. Next up: Minimum Spanning Trees: Kruskal and Prim.
Part 1 · Introduction to weighted shortest paths
Weights and relaxation
A map app, a delivery planner and a network router all ask the same thing: the cheapest way from here to there, where each road, link or hop has its own cost. Breadth-first search counts hops, so it answers a different question as soon as costs differ.
In a weighted graph every edge carries a weight: minutes, rupees, kilometres or a probability. The cost of a path is the sum of the weights along it, and a shortest path is one of least cost, which need not have the fewest edges. A direct road of 10 minutes loses to two roads of 2 and 3. This chapter solves the single-source problem: the cheapest cost from one start node to every other node. Nodes are numbered 0 to n - 1, and an edge is a triple [from, to, weight].
// A directed weighted edge: [from, to, weight]. Nodes are 0 to n - 1. export type Edge = [number, number, number] // adj[u] lists [v, weight] for every edge leaving u. export type Adj = [number, number][][] export function buildAdj(n: number, edges: Edge[]): Adj { const adj: Adj = Array.from({ length: n }, () => []) const ok = (x: number) => Number.isInteger(x) && x >= 0 && x < n for (const [u, v, w] of edges) { if (!ok(u) || !ok(v)) throw new RangeError(`edge ${u}->${v} is outside 0..${n - 1}`) if (Number.isNaN(w)) throw new RangeError(`edge ${u}->${v} has no weight`) adj[u].push([v, w]) } return adj }
graph.ts: edges and adjacency lists