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;
    }
}
相关推荐
aini_lovee18 小时前
FMCW雷达测速测距系统(锯齿波 + CFAR检测)
算法
qq_2975746718 小时前
设计模式系列文章(基础篇第 11 篇):模板方法模式——定义算法骨架,实现代码复用与流程统一
算法·设计模式·模板方法模式
lqqjuly18 小时前
知识蒸馏:理论、算法与可运行实现
人工智能·深度学习·算法
水上冰石18 小时前
comfui的sd1.5模型,有多少采样算法,详解每一个采样算法
人工智能·算法
黎阳之光18 小时前
视频孪生+空天地水工融合,黎阳之光构建智慧水利监测新范式
大数据·人工智能·物联网·算法·安全
cheems952718 小时前
[算法手记] 贪心 爬楼梯问题
算法·贪心算法
KaMeidebaby19 小时前
卡梅德生物技术快报|酵母双杂交 cDNA 文库构建与蛋白互作筛选流程
服务器·前端·数据库·人工智能·算法
sheeta199819 小时前
LeetCode 每日一题笔记 日期:2026.05.27 题目:3121. 统计特殊字母的数量 II
笔记·算法·leetcode
ST——Jess19 小时前
年度行业趋势研究报告:泛心理数字化赛道“流日推演”的算法困境与高保真交互范式重构
人工智能·算法·架构
Tisfy19 小时前
LeetCode 3300.替换为数位和以后的最小元素:一次遍历
数学·算法·leetcode·模拟