题目
https://www.lintcode.com/problem/1002
java
给定一个巴士路线列表 routes. routes[i] 是第 i 辆巴士的循环路线. 例如, 如果 routes[0] = [1, 5, 7], 那么第一辆巴士按照 1 -> 5 -> 7 -> 1 -> 5 -> 7 ... 的路径不停歇地行进.
给定 S 和 T, 问在仅仅乘巴士的情况下, 从 S 赶到 T 最少乘多少辆不同的巴士? 如果无法赶到, 返回 -1.
1 <= routes.length <= 500
1 <= routes[i].length <= 500
0 <= routes[i][j] < 10 ^ 6
样例
样例 1:
输入: routes = [[1, 2, 7], [3, 6, 7]], S = 1, T = 6
输出: 2
解释: 坐第一辆车到 7, 然后坐第二辆车到 6.
样例 2:
输入: routes = [[1], [15, 16, 18], [3, 4,12,14]], S = 3, T = 15
输出: -1
解释: 没有从 3 到 15 的路线.
思路
bfs
答案
java
public class Solution {
/**
* @param routes: a list of bus routes
* @param s: start
* @param t: destination
* @return: the least number of buses we must take to reach destination
*/
public int numBusesToDestination(int[][] routes, int s, int t) {
//和825题差不多
Map<Integer, List<Integer>> stopmap = new HashMap<>();
Map<Integer, List<Integer>> carmap = new HashMap<>();
for (int i = 0; i <routes.length ; i++) {
for (int j = 0; j < routes[i].length; j++) {
int stop = routes[i][j]; //车站
int car = i; //第i辆车
if(!stopmap.containsKey(stop))
stopmap.put(stop,new ArrayList<>());
if(!carmap.containsKey(car))
carmap.put(car,new ArrayList<>());
stopmap.get(stop).add(car);
carmap.get(car).add(stop);
}
}
Queue<Integer> q = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
q.add(s);
visited.add(s);
int steps = 0;
while (!q.isEmpty()){
steps++;
int size = q.size();
for (int i = 0; i <size ; i++) {
int stop = q.poll();
if(stop == t)
return steps-1;
for (int sp : stopmap.get(stop)) {
for (int c : carmap.get(sp)) {
if(visited.contains(c)) continue;
q.add(c);
visited.add(c);
}
}
}
}
return -1;
}
}