バス路線のリストがあります。それぞれ routes[i]
がi番目のバスが永遠に繰り返すバスルートです。たとえばの場合 routes[0] = [1, 5, 7]
、これは最初のバス(0番目にインデックスが付けられている)が1-> 5-> 7-> 1-> 5-> 7-> 1-> ...のシーケンスで永遠に移動することを意味します。
私たちはバス停S
(最初はバスに乗っていません)から出発し、バス停 に行きたいです T
。バスのみで旅行する場合、目的地に到着するために必要なバスの最小数はいくつですか?それが不可能な場合は-1を返します。
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.
アイデア:この質問の意味は次のとおりです。同じバス路線は1つの列車として数えられます。これは1ステップにすぎません。次のレイヤーは、ヘッドステーションのすべてのバス路線駅を収集することです。
時間:O(V + E); スペース:O(V);
注:1.同じバスは1度だけ座る必要があるため、訪問先には駅ではなくバスが含まれます。
2.同じラインが同じバスに属し、1回だけカウントされるため、同じラインのすべてを次のレイヤーに配置します。
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;
}
}