-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0815-bus-routes.js
More file actions
82 lines (69 loc) · 2.23 KB
/
0815-bus-routes.js
File metadata and controls
82 lines (69 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Bus Routes
* Time Complexity: O(S_total + R)
* Space Complexity: O(S_total + R)
*/
var numBusesToDestination = function (inputRoutes, startStop, endStop) {
if (startStop === endStop) return 0;
const stopToRouteConnections = new Map();
let routeLoopIndex = 0;
while (routeLoopIndex < inputRoutes.length) {
const currentRouteStops = inputRoutes[routeLoopIndex];
let stopInRouteIndex = 0;
while (stopInRouteIndex < currentRouteStops.length) {
const currentStationValue = currentRouteStops[stopInRouteIndex];
if (!stopToRouteConnections.has(currentStationValue)) {
stopToRouteConnections.set(currentStationValue, []);
}
stopToRouteConnections.get(currentStationValue).push(routeLoopIndex);
stopInRouteIndex++;
}
routeLoopIndex++;
}
if (
!stopToRouteConnections.has(startStop) ||
!stopToRouteConnections.has(endStop)
) {
return -1;
}
const seenRouteIdentifiers = new Set();
const visitedBusStops = new Set([startStop]);
const bfsQueue = [[startStop, 0]];
while (bfsQueue.length > 0) {
const [currentDequeuedStop, busesTakenCount] = bfsQueue.shift();
if (currentDequeuedStop === endStop) {
return busesTakenCount;
}
const busesFromThisStop = stopToRouteConnections.get(currentDequeuedStop);
let busIterIndex = 0;
for (
busIterIndex = 0;
busIterIndex < busesFromThisStop.length;
busIterIndex++
) {
const busIdConsidered = busesFromThisStop[busIterIndex];
if (seenRouteIdentifiers.has(busIdConsidered)) {
continue;
}
seenRouteIdentifiers.add(busIdConsidered);
const stopsOnConsideredBus = inputRoutes[busIdConsidered];
let stopIterIndex = 0;
for (
stopIterIndex = 0;
stopIterIndex < stopsOnConsideredBus.length;
stopIterIndex++
) {
const nextStationCandidate = stopsOnConsideredBus[stopIterIndex];
if (nextStationCandidate === endStop) {
return busesTakenCount + 1;
}
if (visitedBusStops.has(nextStationCandidate)) {
continue;
}
visitedBusStops.add(nextStationCandidate);
bfsQueue.push([nextStationCandidate, busesTakenCount + 1]);
}
}
}
return -1;
};