题目简介:
给你一个数组 routes ,表示一系列公交线路,其中每个 routes[i] 表示一条公交线路,第 i 辆公交车将会在上面循环行驶。
例如,路线 routes[0] = [1, 5, 7] 表示第 0 辆公交车会一直按序列 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... 这样的车站路线行驶。
现在从 source 车站出发(初始时不在公交车上),要前往 target 车站。 期间仅可乘坐公交车。
求出 最少乘坐的公交车数量 。如果不可能到达终点车站,返回 -1 。
解题思路:
要求出需要乘坐的公交车的最少数量,那么每辆车只能乘坐一次。通过数组dist对已乘坐车辆进行记录。queue记录当前乘坐的车辆。stopToRoutes记录每个站点对应车辆。每次遍历时初始车辆经过的每个站进行广度搜索,并将对应车辆加入遍历队列,并将已经走过的站删除(防止重乘坐经过该站的公交),直到有一辆车经过目标站。
package BFS;
import java.util.*;
public class question_815 {
public static void main(String[] args) {
int[][] array = {
{1, 2, 7},
{3, 6, 7}
};
int source = 1, target = 6;
Solution_815 sol = new Solution_815();
System.out.println(sol.numBusesToDestination(array, source, target));
}
}
class Solution_815 {
public int numBusesToDestination(int[][] routes, int source, int target) {
//排查source==target
if(source == target){
return 0;
}
int n = routes.length;
Queue<Integer> queue = new ArrayDeque<>();//存储公交车编号
Map<Integer,List<Integer>> stopToRoutes = new HashMap<>();//存储每个站点对应的公交车序号
int[] dist = new int[n];// 最短距离数组
Arrays.fill(dist, Integer.MAX_VALUE); // 初始化距离为无穷大
for (int i=0; i < n; i++){
for(int stop : routes[i]){
if(stop == source){
queue.offer(i);//将初始公交放入队列
dist[i] = 1;//起始乘坐公交数为1
}
stopToRoutes.computeIfAbsent(stop, k -> new ArrayList<>()).add(i);//向对应站点添加公交车
}
}
//BFS,广度优先搜索
while(!queue.isEmpty()){
int bus = queue.poll();
for(int stop : routes[bus]){
if(stop == target){
return dist[bus];
}
if(stopToRoutes.containsKey(stop)){
for(int nextBus : stopToRoutes.get(stop)){
if(dist[nextBus] > dist[bus] + 1){
dist[nextBus] = dist[bus] + 1;//更新到nextBus的最少乘车数
queue.offer(nextBus);//添加新公交
}
stopToRoutes.remove(stop);//删除已访问节点
}
}
}
}
return -1;
}
}