We have a list of bus routes. Eachroutes[i]
is a bus route that the i-th bus repeats forever. For example ifroutes[0] = [1, 5, 7]
, this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.
We start at bus stopS
(initially not on a bus), and we want to go to bus stopT
. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.
Example:
Input:
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 6
Output:
2
Explanation:
The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
Note:
1
<
= routes.length
<
= 500
.1
<
= routes[i].length
<
= 500
.0
<
= routes[i][j]
<
10 ^ 6
.tag: BFS
class Solution {
private class Point{
int node;
int depth;
public Point(int node, int depth){
this.node = node;
this.depth = depth;
}
}
public int numBusesToDestination(int[][] routes, int S, int T) {
int n = routes.length;
if (S == T) return 0;
Map<Integer, Set<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; i++){
Arrays.sort(routes[i]);
graph.put(i, new HashSet<>());
}
for (int i = 0; i < n; i++){
for (int j = i + 1; j < n; j++){
if (intersect(routes[i], routes[j])){
graph.get(i).add(j);
graph.get(j).add(i);
}
}
}
Set<Integer> targets = new HashSet<>();
Queue<Point> q = new LinkedList<>();
Set<Integer> seen = new HashSet<>();
for (int i = 0; i < n; i++){
if (Arrays.binarySearch(routes[i], S) >= 0){
seen.add(i);
q.offer(new Point(i, 0));
}
if (Arrays.binarySearch(routes[i], T) >= 0){
targets.add(i);
}
}
while (!q.isEmpty()){
Point cur = q.poll();
int node = cur.node, depth = cur.depth;
if (targets.contains(node)) return depth + 1;
for (int nei : graph.get(node)){
if (seen.contains(nei)) continue;
seen.add(nei);
q.offer(new Point(nei, depth + 1));
}
}
return -1;
}
public boolean intersect(int[] A, int[] B) {
int i = 0, j = 0;
while (i < A.length && j < B.length) {
if (A[i] == B[j]) return true;
if (A[i] < B[j]) i++; else j++;
}
return false;
}
}