|
| 1 | +/** |
| 2 | + * 815. Bus Routes |
| 3 | + * https://leetcode.com/problems/bus-routes/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array routes representing bus routes where routes[i] is a bus route that |
| 7 | + * the ith bus repeats forever. |
| 8 | + * |
| 9 | + * For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence |
| 10 | + * 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever. |
| 11 | + * |
| 12 | + * You will start at the bus stop source (You are not on any bus initially), and you want to |
| 13 | + * go to the bus stop target. You can travel between bus stops by buses only. |
| 14 | + * |
| 15 | + * Return the least number of buses you must take to travel from source to target. |
| 16 | + * |
| 17 | + * Return -1 if it is not possible. |
| 18 | + */ |
| 19 | + |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[][]} routes |
| 23 | + * @param {number} source |
| 24 | + * @param {number} target |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var numBusesToDestination = function(routes, source, target) { |
| 28 | + if (source === target) return 0; |
| 29 | + |
| 30 | + const stopToBuses = new Map(); |
| 31 | + |
| 32 | + for (let busId = 0; busId < routes.length; busId++) { |
| 33 | + for (const stop of routes[busId]) { |
| 34 | + if (!stopToBuses.has(stop)) { |
| 35 | + stopToBuses.set(stop, []); |
| 36 | + } |
| 37 | + stopToBuses.get(stop).push(busId); |
| 38 | + } |
| 39 | + } |
| 40 | + if (!stopToBuses.has(source) || !stopToBuses.has(target)) return -1; |
| 41 | + |
| 42 | + const visitedBuses = new Set(); |
| 43 | + const visitedStops = new Set([source]); |
| 44 | + const queue = [[source, 0]]; |
| 45 | + |
| 46 | + while (queue.length > 0) { |
| 47 | + const [currentStop, busCount] = queue.shift(); |
| 48 | + if (currentStop === target) return busCount; |
| 49 | + for (const busId of stopToBuses.get(currentStop)) { |
| 50 | + if (visitedBuses.has(busId)) continue; |
| 51 | + visitedBuses.add(busId); |
| 52 | + for (const nextStop of routes[busId]) { |
| 53 | + if (visitedStops.has(nextStop)) continue; |
| 54 | + visitedStops.add(nextStop); |
| 55 | + queue.push([nextStop, busCount + 1]); |
| 56 | + if (nextStop === target) return busCount + 1; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return -1; |
| 62 | +}; |
0 commit comments