lintcode 1002 · 巴士路线【中等 BFS 和825题一样】

题目

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;
    }
}
相关推荐
超级码力6664 小时前
【Latex文件架构】Latex文件架构模板
算法·数学建模·信息可视化
穿条秋裤到处跑4 小时前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展
Merlos_wind5 小时前
HashMap详解
算法·哈希算法·散列表
汉克老师5 小时前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
Yzzz-F8 小时前
Problem - 2205D - Codeforces
算法
智者知已应修善业8 小时前
【51单片机2个按键控制流水灯运行与暂停】2023-9-6
c++·经验分享·笔记·算法·51单片机
Halo_tjn8 小时前
Java Set集合相关知识点
java·开发语言·算法
生成论实验室9 小时前
《事件关系阴阳博弈动力学:识势应势之道》第四篇:降U动力学——认知确定度的自驱演化
人工智能·科技·神经网络·算法·架构
AI科技星9 小时前
全域数学·72分册:场计算机卷【乖乖数学】
算法·机器学习·数学建模·数据挖掘·量子计算
科研前沿10 小时前
镜像孪生VS视频孪生核心技术产品核心优势
大数据·人工智能·算法·重构·空间计算