JavaScriptFundamental (ES6), part 2
Shortest path with BFS in JavaScript
110 Fewest roads between two cities, and what BFS will not tell you
fairGiven a list of roads between Nigerian cities, build an undirected adjacency map and find the route with the fewest hops between two cities using breadth-first search. Return the whole path, not just its length, by keeping a map of how each city was first reached. Handle a city that cannot be reached at all, and a start that is also the goal. Then prove two things: that marking a city seen when you queue it rather than when you visit it saves real work, and that fewest hops is not the same as shortest distance.
Stuck? Three hints, smallest first
- 1. The queue holds cities to visit. Alongside it keep a
Mapfrom each city to the city you reached it from, and the path falls out by walking that map backwards from the goal. - 2. Mark a city as seen at the moment you push it. Wait until you pop it and the same city gets pushed once per edge that points at it.
- 3. Breadth-first search counts edges, so it is only a shortest path when every edge costs the same. Give one road a length and the answer changes.
const roads = [
['Lagos', 'Ibadan', 130],
['Ibadan', 'Ilorin', 160],
['Ibadan', 'Benin', 300],
['Lagos', 'Benin', 320],
['Ilorin', 'Abuja', 350],
['Ilorin', 'Lokoja', 250],
['Benin', 'Onitsha', 130],
['Benin', 'Lokoja', 290],
['Onitsha', 'Enugu', 110],
['Enugu', 'Makurdi', 240],
['Lokoja', 'Abuja', 200],
['Lokoja', 'Makurdi', 260],
['Abuja', 'Kaduna', 190],
['Kaduna', 'Kano', 230],
['PortHarcourt', 'Yenagoa', 90],
];
function buildGraph(list) {
const adjacent = new Map();
const lengths = new Map();
const link = (from, to) => {
if (!adjacent.has(from)) adjacent.set(from, []);
adjacent.get(from).push(to);
};
for (const [a, b, km] of list) {
link(a, b);
link(b, a);
lengths.set(a + '|' + b, km);
lengths.set(b + '|' + a, km);
}
return { adjacent, lengths };
}
const { adjacent, lengths } = buildGraph(roads);
const kmOf = (path, table) => {
let total = 0;
for (let i = 1; i < path.length; i++) total += table.get(path[i - 1] + '|' + path[i]);
return total;
};
// Seen is set at push time. The counter is how many pushes that costs.
function shortestHops(adjacent, start, goal) {
if (!adjacent.has(start) || !adjacent.has(goal)) return { path: null, hops: -1, pushes: 0 };
const cameFrom = new Map([[start, null]]);
const levels = new Map([[start, 0]]);
let queue = [start];
let pushes = 1;
while (queue.length) {
const next = [];
for (const city of queue) {
if (city === goal) {
const path = [];
for (let at = goal; at !== null; at = cameFrom.get(at)) path.unshift(at);
return { path, hops: path.length - 1, pushes, levels };
}
for (const neighbour of adjacent.get(city)) {
if (cameFrom.has(neighbour)) continue; // already queued by somebody
cameFrom.set(neighbour, city);
levels.set(neighbour, levels.get(city) + 1);
next.push(neighbour);
pushes++;
}
}
queue = next;
}
return { path: null, hops: -1, pushes, levels };
}
// The same walk, but a city is only marked seen once it is popped.
function lateMarking(adjacent, start, goal) {
const seen = new Set();
const queue = [start];
let pushes = 1;
let popped = 0;
while (queue.length) {
const city = queue.shift();
popped++;
if (seen.has(city)) continue;
seen.add(city);
if (city === goal) return { pushes, popped, reached: true };
for (const neighbour of adjacent.get(city)) {
if (seen.has(neighbour)) continue;
queue.push(neighbour);
pushes++;
}
}
return { pushes, popped, reached: false };
}
const toKano = shortestHops(adjacent, 'Lagos', 'Kano');
const levelSpread = [toKano.levels.size, toKano.levels.get('Abuja'), toKano.levels.get('Kano'), toKano.levels.has('Yenagoa')];
const sameCity = shortestHops(adjacent, 'Lagos', 'Lagos');
const unreachable = shortestHops(adjacent, 'Lagos', 'Yenagoa');
const notOnTheMap = shortestHops(adjacent, 'Lagos', 'Sokoto');
const late = lateMarking(adjacent, 'Lagos', 'Kano');
const pushComparison = [toKano.pushes, late.pushes, late.pushes > toKano.pushes];
let symmetric = true;
let directedEntries = 0;
for (const [city, neighbours] of adjacent) {
directedEntries += neighbours.length;
for (const n of neighbours) if (!adjacent.get(n).includes(city)) symmetric = false;
}
const component = (start) => {
const seen = new Set([start]);
const queue = [start];
while (queue.length) {
for (const n of adjacent.get(queue.shift())) if (!seen.has(n)) { seen.add(n); queue.push(n); }
}
return seen.size;
};
const twoComponents = [component('Lagos'), component('Yenagoa')];
// One long straight road, and fewest hops stops being cheapest.
const expressway = buildGraph([...roads, ['Lagos', 'Abuja', 750]]);
const byHops = shortestHops(expressway.adjacent, 'Lagos', 'Abuja');
const viaIbadan = ['Lagos', 'Ibadan', 'Ilorin', 'Abuja'];
const hopsVsKm = [byHops.hops, kmOf(byHops.path, expressway.lengths), viaIbadan.length - 1, kmOf(viaIbadan, expressway.lengths)];
console.log('Lagos to Kano :', toKano.path.join(' -> '), '=', toKano.hops, 'hops');
console.log('levels :', levelSpread);
console.log('pushes :', pushComparison);
console.log('hops vs km :', hopsVsKm);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the fewest-hops route to Kano is found whole, not just measured', [toKano.path, toKano.hops], [['Lagos', 'Ibadan', 'Ilorin', 'Abuja', 'Kaduna', 'Kano'], 5]);
test('the level map records how far every reachable city is, and omits the rest', levelSpread, [11, 3, 5, false]);
test('a start that is also the goal is a path of one city and no hops', [sameCity.path, sameCity.hops], [['Lagos'], 0]);
test('a city in another component, and a city not on the map at all, both give null', [unreachable.path, notOnTheMap.path, notOnTheMap.pushes], [null, null, 0]);
test('the graph really is undirected: every road appears in both lists', [symmetric, directedEntries], [true, 30]);
test('marking at push time queues each city once; marking at pop time queues more', pushComparison, [11, 15, true]);
test('and the late version pops cities it has already dealt with', late.popped > 11, true);
test('the two components are 11 cities and 2, which is why Yenagoa is unreachable', twoComponents, [11, 2]);
test('fewest hops is not shortest distance: one hop of 750km beats three totalling 640km on hops alone', hopsVsKm, [1, 750, 3, 640]);
Breadth-first search answers "fewest edges" and nothing else. The last assertion is that limitation stated as plainly as it can be: with an expressway in the graph, BFS reports a one-hop route of 750km and is entirely correct, while a driver would take the three-hop route of 640km. The moment edges have different costs you need Dijkstra, which is the same walk with a priority queue instead of a plain one — exercise 109 built the queue it needs.
The cameFrom map is what turns a search into an answer. Recording the city you arrived from, at the moment you first queue a city, gives a tree of first-arrivals; walking it backwards from the goal reconstructs the route. Because BFS reaches every city by the shortest hop count, the first arrival is the one worth keeping, which is why the map is written once and never updated.
The push comparison is the mistake almost everybody makes once. Marking a city seen when you pop it looks equivalent and is not: between being queued and being popped, every other edge pointing at that city queues it again, so the queue holds duplicates and grows with the edge count rather than the city count. Here it is 15 pushes instead of 11 on a graph of 15 roads, and cities popped a second time only to be skipped; on a dense graph the queue grows with the edge count rather than the city count, which is the difference between linear and quadratic. Mark at push time, always.