-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbusroutes.cpp
37 lines (36 loc) · 839 Bytes
/
busroutes.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
int numBusesToDestination(vector<vector<int>>& routes, int s, int t)
{
unordered_map<int,vector<int>> adj;
for(int i=0;i<routes.size();++i)
for(int x:routes[i])
if(adj.find(x)==adj.end())
adj[x]={i};
else adj[x].push_back(i);
unordered_set<int> grey;
unordered_set<int> grey_routes;
queue<pair<int,int>> q;
q.push({s,0});
grey.insert(s);
while(!q.empty())
{
auto temp=q.front();
q.pop();
s=temp.first;
int ret=temp.second;
if(s==t)
return ret;
else
for(int r:adj[s])
if(grey_routes.find(r)==grey_routes.end())
{
for(int v:routes[r])
if(grey.find(v)==grey.end())
{
q.push({v,ret+1});
grey.insert(v);
}
grey_routes.insert(r);
}
}
return -1;
}