自学内容网 自学内容网

力扣(leetcode)每日一题 815 公交路线 (图的宽度优先遍历变种)

815. 公交路线 - 力扣(LeetCode)

题干

给你一个数组 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

解法

首先,你需要一个车站对应公交车列表的hashmap
然后,你得到出发点车站。将对应的公交车列表都取出来,对应公交车列表对应的所有站台都拿出来。然后阶段距离。 一次类推。
也就是原来是点和点之间的连接,这里多了一层中介,就是公交车站台。




    public static int numBusesToDestination(int[][] routes, int source, int target) {
        if (source == target) { // 目的地和出发点重合,且公交车不经过改地点
            return 0;
        }
        // routes  公交车对应的是目车站列表
        // 数值和车站
        HashMap<Integer, List<Integer>> map = new HashMap<>(); // 车站对应的公交车列表
        for (int i = 0; i < routes.length; i++) {
            int[] route = routes[i];
            for (int key : route) {
                List<Integer> list = map.getOrDefault(key, new ArrayList<>());
                list.add(i);
                map.put(key, list);
            }
        }
        if (map.get(source) == null || map.get(target) == null) {
            return -1;
        }

        HashSet<Integer> set = new HashSet<>(); // 这里记录

        HashMap<Integer, Integer> dict = new HashMap<>();
        // ArrayDeque
        ArrayDeque<Integer> deque = new ArrayDeque<>();
        dict.put(source, 0);
        deque.add(source); // 车站出发点
        while (!deque.isEmpty()) {
            Integer pointx = deque.poll();  // 弹出车站
            Integer distance = dict.get(pointx);
            List<Integer> list = map.get(pointx);  // 得到公交车列表
            for (int i = 0; i < list.size(); i++) {
                Integer car = list.get(i); // 获取公交车
                if (!set.contains(car)) {  // 这个公交车没有用过
                    int[] route = routes[car];   // 得到所有对应的车子
                    for (int j = 0; j < route.length; j++) {
                        int pointy = route[j];
                        if (!dict.containsKey(pointy)) {
                            dict.put(pointy, distance + 1);
                            deque.add(pointy);
                        }
                    }
                    set.add(car);
                }
            }
        }
        if (dict.get(target) != null) {
            return dict.get(target);
        }
        return -1;
    }

原文地址:https://blog.csdn.net/ganjiee0007/article/details/142408317

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!