-
Notifications
You must be signed in to change notification settings - Fork 0
/
815.bus-routes.cpp
47 lines (44 loc) · 1.27 KB
/
815.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
43
44
45
46
47
/*
* @lc app=leetcode id=815 lang=cpp
*
* [815] Bus Routes
*/
// @lc code=start
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int source,
int target) {
unordered_map<int, vector<int>> busStops;
for (int i = 0; i < routes.size(); i++) {
for (int stop : routes[i]) {
busStops[stop].push_back(i);
}
}
int ans = 0;
queue<int> q;
set<int> busHadTaken;
q.push(source);
while (!q.empty()) {
int size = q.size();
while (size--) {
int current = q.front();
q.pop();
cout << "current: " << current << ", ";
if (current == target) return ans;
for (int bus : busStops[current]) {
if (busHadTaken.count(bus)) continue;
cout << bus << " ";
busHadTaken.insert(bus);
for (int nextStop : routes[bus]) {
if (nextStop == current) continue;
q.push(nextStop);
}
}
}
ans++;
cout << endl;
}
return -1;
}
};
// @lc code=end