2
* @param {number[][]} routes3
* @param {number} source4
* @param {number} target7
var numBusesToDestination = function (routes, source, target) {8
// This map will hold an adjacency map of all the routes each stop can go to9
let stopRoutes = new Map();11
// Initialize adjacency map - for each route12
for (let route = 0; route < routes.length; route++) {13
// Look at all of the route's stops14
for (let stop of routes[route]) {15
// If we haven't added this stop yet then create a new entry for it16
if (!stopRoutes.has(stop)) stopRoutes.set(stop, new Set());17
// Add the current route as a possible route this stop can go to18
stopRoutes.get(stop).add(route);22
// This queue will contain all of the visited stops AND the number of buses it took to get to that stop23
let stopsToVisit = new Queue();24
// We start at the source and 0 buses to get there25
stopsToVisit.enqueue([source, 0]);27
// This set will contain all of the stops we've already visited28
let visitedStops = new Set();29
visitedStops.add(source);31
// This set will contain all of the routes we've visited32
let visitedRoutes = new Array(routes.length);34
// While there are more stops to visit35
while (!stopsToVisit.isEmpty()) {36
// Get the queued stop and number of buses it took to get there37
let stop = stopsToVisit.front()[0],38
bus = stopsToVisit.front()[1];39
stopsToVisit.dequeue();41
// If the stop is our target then we return the number of buses it took to get here42
if (stop === target) return bus;44
// Loop over all the routes this stop can go to45
for (let route of stopRoutes.get(stop)) {46
// If we've already visited this route then don't do it again47
if (visitedRoutes[route]) continue;49
// Loop over all of the stops in this route50
for (let stop of routes[route]) {51
// If we haven't visited this stop before52
if (!visitedStops.has(stop)) {53
// Add it to the stops we've visited54
visitedStops.add(stop);55
// Add it to the queue of stops we need to visit adding 1 more bus stop to get to it56
stopsToVisit.enqueue([stop, bus + 1]);60
// Set the current route as visited61
visitedRoutes[route] = true;65
// If we never got to our target then return -1