forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bus-routes.cpp
42 lines (40 loc) · 1.25 KB
/
bus-routes.cpp
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
// Time: O(|V| + |E|)
// Space: O(|V| + |E|)
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {
if (S == T) {
return 0;
}
unordered_map<int, unordered_set<int>> to_route;
for (int i = 0; i < routes.size(); ++i) {
for (const auto& stop : routes[i]) {
to_route[stop].emplace(i);
}
}
int result = 1;
vector<int> q{S};
unordered_set<int> lookup{S};
while (!q.empty()) {
vector<int> next_q;
for (const auto& stop : q) {
for (const auto& i : to_route[stop]) {
for (const auto& next_stop : routes[i]) {
if (lookup.count(next_stop)) {
continue;
}
if (next_stop == T) {
return result;
}
next_q.emplace_back(next_stop);
to_route[next_stop].erase(i);
lookup.emplace(next_stop);
}
}
}
swap(q, next_q);
++result;
}
return -1;
}
};