-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathBus Routes.java
39 lines (39 loc) · 1.34 KB
/
Bus Routes.java
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
class Solution {
public int numBusesToDestination(int[][] routes, int source, int target) {
if (source == target) {
return 0;
}
Map<Integer, Set<Integer>> stopToBusMapping = new HashMap<>();
for (int i = 0; i < routes.length; i++) {
for (int stop : routes[i]) {
stopToBusMapping.computeIfAbsent(stop, k -> new HashSet<>()).add(i);
}
}
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
for (int route : stopToBusMapping.get(source)) {
queue.add(route);
visited.add(route);
}
int buses = 1;
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
int removed = queue.remove();
for (int stop : routes[removed]) {
if (stop == target) {
return buses;
}
for (int nextBus : stopToBusMapping.getOrDefault(stop, new HashSet<>())) {
if (!visited.contains(nextBus)) {
visited.add(nextBus);
queue.add(nextBus);
}
}
}
}
buses++;
}
return -1;
}
}