Bus Routes

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 线路的只算一趟车,也就是算一步而已, station 是node,那么下一层就是这个station属于哪几条line,这几条line上面的所有的station就是下一层,也就是这个station,可以转乘到哪几条其他的line上面;Time: O(V + E); Space: O(V);

class Solution {
    public int numBusesToDestination(int[][] routes, int source, int target) {
        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<>();
        queue.offer(source);
        HashSet<Integer> visited = new HashSet<>();
        int step = 0;
        
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                Integer node = queue.poll();
                if(node == target) {
                    return step;
                }
                if(graph.get(node) != null) {
                    for(Integer bus: graph.get(node)) {
                        if(!visited.contains(bus)) {
                            visited.add(bus);
                            // add的是下一层bus的station;
                            for(int j = 0; j < routes[bus].length; j++) {
                                queue.offer(routes[bus][j]);
                            }
                        }
                    }
                }
            }
            step++;
        }
        return -1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值