-
Notifications
You must be signed in to change notification settings - Fork 1
/
BusRoutes.java
71 lines (69 loc) · 2.17 KB
/
BusRoutes.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
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
import java.util.*;
/**
* 815. Bus Routes
* BFS
* @author LBW
*/
public class BusRoutes {
public int numBusesToDestination(int[][] routes, int source, int target) {
if (source == target)
return 0;
List<Set<Integer>> stations = new ArrayList<>();
List<List<Integer>> graph = new ArrayList<>();
int m = routes.length;
for (int i = 0; i < m ; i++) {
stations.add(new HashSet<>());
for (int j = 0; j < routes[i].length; j++) {
stations.get(i).add(routes[i][j]);
}
graph.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
for (int j = i + 1; j < m; j++) {
if (interact(stations.get(i), stations.get(j))) {
graph.get(i).add(j);
graph.get(j).add(i);
}
}
}
boolean[] hasVisited = new boolean[m];
Queue<Integer> queue = new ArrayDeque<>();
Set<Integer> targets = new HashSet<>();
for (int i = 0; i < m; i++) {
if (stations.get(i).contains(target)) {
targets.add(i);
}
}
int cur = 1;
for (int i = 0; i < m; i++) {
if (stations.get(i).contains(source)) {
if (targets.contains(i)) {
return cur;
}
queue.offer(i);
hasVisited[i] = true;
}
}
while (!queue.isEmpty()) {
int size = queue.size();
cur += 1;
for (int i = 0; i < size; i++) {
int bus = queue.poll();
for (int next: graph.get(bus)) {
if (targets.contains(next))
return cur;
if (!hasVisited[next]) {
queue.offer(next);
hasVisited[next] = true;
}
}
}
}
return -1;
}
private boolean interact(Set<Integer> set1, Set<Integer> set2) {
Set<Integer> result = new HashSet<>(set1);
result.retainAll(set2);
return !result.isEmpty();
}
}