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;
    }
}
相关推荐
康谋自动驾驶9 分钟前
康谋分享 | 自动驾驶仿真进入“标准时代”:aiSim全面对接ASAM OpenX
人工智能·科技·算法·机器学习·自动驾驶·汽车
C++ 老炮儿的技术栈1 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
yychen_java1 小时前
R-tree详解
java·算法·r-tree
MarkHard1232 小时前
Leetcode (力扣)做题记录 hot100(62,64,287,108)
算法·leetcode·职场和发展
一只鱼^_3 小时前
牛客练习赛138(首篇万字题解???)
数据结构·c++·算法·贪心算法·动态规划·广度优先·图搜索算法
一只码代码的章鱼3 小时前
Spring的 @Validate注解详细分析
前端·spring boot·算法
邹诗钰-电子信息工程3 小时前
嵌入式自学第二十一天(5.14)
java·开发语言·算法
↣life♚3 小时前
从SAM看交互式分割与可提示分割的区别与联系:Interactive Segmentation & Promptable Segmentation
人工智能·深度学习·算法·sam·分割·交互式分割
zqh176736464694 小时前
2025年阿里云ACP人工智能高级工程师认证模拟试题(附答案解析)
人工智能·算法·阿里云·人工智能工程师·阿里云acp·阿里云认证·acp人工智能
fie88894 小时前
用模型预测控制算法实现对电机位置控制仿真
算法