[LeetCode] Bus Routes

815. Bus Routes

You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.

  • For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> … forever.

You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.

Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.

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
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {
if(source == target) return 0;
unordered_map<int, vector<int>> g;
for(int i = 0; i < routes.size(); i++) {
for(auto stop : routes[i]) {
g[stop].push_back(i);
}
}
unordered_set<int> v{source};
int time = 1;
queue<int> q;
q.push(source);
while(!q.empty()) {
int sz = q.size();
while(sz--) {
auto stop = q.front(); q.pop();
for(auto r : g[stop]) {
for(auto next : routes[r]) {
if(!v.count(next)) {
q.push(next);
v.insert(next);
if(next == target)
return time;
}
}
routes[r].clear();
}
}
++time;
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/bus-routes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.