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;
    }
}
相关推荐
午彦琳8 分钟前
2026.9.11
数据结构·python·算法
302wanger1 小时前
蛋炒饭周刊 · 第 1 期(2026-09-07至2026-09-11)
算法
shehuiyuelaiyuehao1 小时前
算法43,外观数列,模拟算法+双指针
java·算法
alphaTao2 小时前
LeetCode 每日一题 2026/9/7-2026/9/13
算法·leetcode
kanhaoning2 小时前
Agent 记忆出现重复和矛盾怎么优化:我实测了6种去重和更新策略,找到了低成本维护记忆质量的方法
算法
hans汉斯2 小时前
【计算机科学与应用】层级评论上下文依赖识别数据集构建与研究——以小红书旅游评论数据为例
人工智能·算法·yolo·目标检测·cnn·旅游
码行山野赴时序归途2 小时前
顺序表(Sequential List)详解:从数组到 C 语言实现
c语言·开发语言·数据结构·算法
Lokey8683 小时前
自注意力机制与多头注意力机制
算法
linx2953 小时前
单元七 · 零基础路线图-第 1–3 周·变量、类型与字符串
c语言·开发语言·数据结构·c++·算法