Skip to content

Commit 764e2b5

Browse files
committed
Add solution #815
1 parent e744ed7 commit 764e2b5

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,7 @@
623623
812|[Largest Triangle Area](./0812-largest-triangle-area.js)|Easy|
624624
813|[Largest Sum of Averages](./0813-largest-sum-of-averages.js)|Medium|
625625
814|[Binary Tree Pruning](./0814-binary-tree-pruning.js)|Medium|
626+
815|[Bus Routes](./0815-bus-routes.js)|Hard|
626627
819|[Most Common Word](./0819-most-common-word.js)|Easy|
627628
821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy|
628629
824|[Goat Latin](./0824-goat-latin.js)|Easy|

Diff for: solutions/0815-bus-routes.js

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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

Comments
 (0)