815. 公交路线
难度困难327
给你一个数组 routes
,表示一系列公交线路,其中每个 routes[i]
表示一条公交线路,第 i
辆公交车将会在上面循环行驶。
- 例如,路线
routes[0] = [1, 5, 7]
表示第0
辆公交车会一直按序列1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...
这样的车站路线行驶。
现在从 source
车站出发(初始时不在公交车上),要前往 target
车站。 期间仅可乘坐公交车。
求出 最少乘坐的公交车数量 。如果不可能到达终点车站,返回 -1
。
示例 1:
输入:routes = [[1,2,7],[3,6,7]], source = 1, target = 6
输出:2
解释:最优策略是先乘坐第一辆公交车到达车站 7 , 然后换乘第二辆公交车到车站 6 。
示例 2:
输入:routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
输出:-1
提示:
1 <= routes.length <= 500
.1 <= routes[i].length <= 105
routes[i]
中的所有值 互不相同sum(routes[i].length) <= 105
0 <= routes[i][j] < 106
0 <= source, target < 106
BFS
题解来自:https://leetcode.cn/problems/bus-routes/solution/luo-by-jefff-r7i0/
**BFS如何保证搜到的一定是换乘数量最少的。**按照路线搜即可:
- 首先让source入队,之后搜所有经过source的路线,将所有经过的节点都入队,如果含有target则直接输出当前的乘车数;否则,继续搜队里的节点。
- 对所有路线维护一个数组判断该路线是否乘坐过,保证每个路线只乘坐过1次。
- 所有路线都乘坐过之后还没有找到target,那么返回-1
暴力遍历每个车站(超时)
class Solution {
public int numBusesToDestination(int[][] routes, int source, int target) {
if(source == target) return 0;
Deque<Integer> dq = new ArrayDeque<>();
dq.addLast(source);
int n = routes.length;
boolean[] visited = new boolean[n+1];
int res = 0;
while(!dq.isEmpty()){
res++;
int m = dq.size();
while(m-- > 0){
int loc = dq.pollFirst();
for(int i = 0; i < n; i++){
if(visited[i]) continue;
int[] route = routes[i];
for(int j = 0; j < route.length; j++){
if(route[j] == loc){
visited[i] = true;
for(int k = 0; k < route.length; k++){
if(route[k] == target) return res;
if(route[k] != loc){
dq.addLast(route[k]);
}
}
}
}
}
}
}
return -1;
}
}
宫水三叶:https://leetcode.cn/problems/bus-routes/solution/gong-shui-san-xie-yi-ti-shuang-jie-po-su-1roh/
换个思路:队列中存放线路id,预处理每个车站可以访问的线路
由于是在边权为 1 的图上求最短路,我们直接使用 BFS
即可。
起始时将「起点车站」所能进入的「路线」进行入队,每次从队列中取出「路线」时,查看该路线是否包含「终点车站」:
- 包含「终点车站」:返回进入该线路所花费的距离
- 不包含「终点车站」:遍历该路线所包含的车站,将由这些车站所能进入的路线,进行入队
class Solution {
int s, t;
int[][] rs;
public int numBusesToDestination(int[][] _rs, int _s, int _t) {
rs = _rs; s = _s; t = _t;
if (s == t) return 0;
int ans = bfs();
return ans;
}
int bfs() {
// 记录某个车站可以进入的路线
Map<Integer, Set<Integer>> map = new HashMap<>();
// 队列存的是经过的路线
Deque<Integer> d = new ArrayDeque<>();
// 哈希表记录的进入该路线所使用的距离
Map<Integer, Integer> m = new HashMap<>();
int n = rs.length;
for (int i = 0; i < n; i++) {
for (int station : rs[i]) {
// 将从起点可以进入的路线加入队列
if (station == s) {
d.addLast(i);
m.put(i, 1);
}
Set<Integer> set = map.getOrDefault(station, new HashSet<>());
set.add(i);
map.put(station, set);
}
}
while (!d.isEmpty()) {
// 取出当前所在的路线,与进入该路线所花费的距离
int poll = d.pollFirst();
int step = m.get(poll);
// 遍历该路线所包含的车站
for (int station : rs[poll]) {
// 如果包含终点,返回进入该路线花费的距离即可
if (station == t) return step;
// 将由该线路的车站发起的路线,加入队列
Set<Integer> lines = map.get(station);
if (lines == null) continue;
for (int nr : lines) {
if (!m.containsKey(nr)) {
m.put(nr, step + 1);
d.add(nr);
}
}
}
}
return -1;
}
}