We have a list of bus routes. Each routes[i]
is a bus route that the i-th bus repeats forever. For example if routes[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 stop S
(initially not on a bus), and we want to go to bus stop T
. 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.
思路:这题的题意是:同一个bus 线路的只算一趟车,也就是算一步而已,那么下一层就是收集head station的所有的busline的站点;
Time: O(V + E); Space: O(V);
注意:1. 同一个bus只需要坐一次;所以visited里面包含的是bus,不是station;
2. 同一个线路,属于同一个bus,只算一次;所以把同一个线路的全部放到下一层;
class Solution {
public int numBusesToDestination(int[][] routes, int S, int T) {
if(routes == null || routes.length == 0 || routes[0].length == 0) {
return -1;
}
HashMap<Integer, HashSet<Integer>> graph = new HashMap<>();
for(int i = 0; i < routes.length; i++) {
for(int j = 0; j < routes[i].length; j++) {
int bus = i;
int station = routes[i][j];
graph.putIfAbsent(station, new HashSet<Integer>());
graph.get(station).add(bus);
}
}
Queue<Integer> queue = new LinkedList<Integer>();
HashSet<Integer> visited = new HashSet<Integer>();
queue.offer(S);
int step = 0;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
Integer head = queue.poll();
if(head == T) {
return step;
}
for(Integer bus: graph.get(head)) {
// 同一个bus只需要坐一次;所以visited里面包含的是bus,不是station;
if(!visited.contains(bus)) {
visited.add(bus);
// 同一个线路,属于同一个bus,只算一次;所以把同一个线路的全部放到下一层;
for(int j = 0; j < routes[bus].length; j++) {
queue.offer(routes[bus][j]);
}
}
}
}
step++;
}
return -1;
}
}