-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBus Routes
85 lines (81 loc) Β· 2.19 KB
/
Bus Routes
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class Solution {
public:
int n;
vector<unordered_set<int>> bus;
void bus_set(vector<vector<int>>& routes) {
bus.resize(n);
int i = 0;
#pragma unroll
for(auto & r: routes)
bus[i++] = unordered_set<int>(r.begin(), r.end());
}
vector<vector<int>> adj;
bool has_intersection(const unordered_set<int>& busX, const unordered_set<int>& busY) {
for (int x: busX){
if (busY.count(x)) return 1;
}
return 0;
}
void build_adj(vector<unordered_set<int>>& bus) {
adj.resize(n);
#pragma unroll
for(int i = 0; i < n-1; i++){
for(int j = i+1; j < n; j++){
if (has_intersection(bus[i], bus[j])){
adj[i].push_back(j);
adj[j].push_back(i);
}
}
}
}
vector<bool> isTarget;
void source_target(int source, int target, queue<int>& q, vector<int>& dist)
{
isTarget.assign(n, 0);
#pragma unroll
for(int i = 0; i < n; i++){
if (bus[i].count(source)){
q.push(i);
dist[i]=1;
}
if (bus[i].count(target))
isTarget[i] = 1;
}
}
void print(auto& c){
for(auto& v: c){
for(int x: v)
cout<<x<<", ";
cout<<endl;
}
}
int numBusesToDestination(vector<vector<int>>& routes, int source, int target)
{
if (source==target) return 0;//edge case
n = routes.size();
bus_set(routes);
// print(bus);
build_adj(bus);
// print(adj);
queue<int> q;
vector<int> dist(n, n+1);
source_target(source, target, q, dist);
while(!q.empty()){
int x = q.front();
int d = dist[x];
// cout<<x<<" d="<<d<<endl;
q.pop();
if (isTarget[x]){
return d;
}
#pragma unroll
for(int y : adj[x]){
if(dist[y] > d + 1){
dist[y] = d + 1;
q.push(y);
}
}
}
return -1;
}
};