-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbusRoutes.cpp
More file actions
39 lines (38 loc) · 1.15 KB
/
busRoutes.cpp
File metadata and controls
39 lines (38 loc) · 1.15 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
// Source: https://leetcode.com/problems/bus-routes/
// Author: Miao Zhang
// Date: 2021-03-13
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {
if (source == target) return 0;
// bus stop: ith bus travel
unordered_map<int, vector<int>> graph;
for (int i = 0; i < routes.size(); i++) {
for (const int u: routes[i]) {
graph[u].push_back(i);
}
}
// ith bus travel
vector<int> visited(routes.size(), 0);
queue<int> q;
q.push(source);
int res = 0;
while (!q.empty()) {
int size = q.size();
res++;
while (size--) {
int stop = q.front();
q.pop();
for (int travel: graph[stop]) {
if (visited[travel]) continue;
visited[travel] = 1;
for (int stop: routes[travel]) {
if (stop == target) return res;
q.push(stop);
}
}
}
}
return - 1;
}
};