forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path815.Bus-Routes_v2.cpp
More file actions
54 lines (45 loc) · 1.47 KB
/
Copy path815.Bus-Routes_v2.cpp
File metadata and controls
54 lines (45 loc) · 1.47 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int S, int T)
{
if (S==T) return 0;
unordered_map<int,vector<int>>stop2bus;
for (int i=0; i<routes.size(); i++)
{
for (auto j: routes[i])
stop2bus[j].push_back(i);
}
unordered_set<int>visitedStop;
unordered_set<int>visitedBus;
queue<int>q;
q.push(S);
visitedStop.insert(S);
int step = -1;
while (!q.empty())
{
step += 1;
int len = q.size();
while (len--)
{
int curStop = q.front();
q.pop();
for (auto bus: stop2bus[curStop])
{
if (visitedBus.find(bus)!=visitedBus.end())
continue;
visitedBus.insert(bus);
for (auto nextStop: routes[bus])
{
if (visitedStop.find(nextStop)!=visitedStop.end())
continue;
if (nextStop==T)
return step+1;
q.push(nextStop);
visitedStop.insert(nextStop);
}
}
}
}
return -1;
}
};