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;
    }
}
相关推荐
小小小CTFER2 分钟前
理论题] 2025 年 “技耀泉城” 海右技能人才大赛网络安全知识竞赛题目(二)
算法·安全·web安全
断剑zou天涯2 小时前
【算法笔记】暴力递归尝试
java·笔记·算法
油泼辣子多加2 小时前
【实战】自然语言处理--长文本分类(1)DPCNN算法
算法·自然语言处理·分类
I'm a winner3 小时前
基于YOLO算法的医疗应用专题:第一章 计算机视觉与深度学习概述
算法·yolo·计算机视觉
vir023 小时前
P1928 外星密码(dfs)
java·数据结构·算法·深度优先·1024程序员节
喜欢吃燃面4 小时前
数据结构算法题:list
开发语言·c++·学习·算法·1024程序员节
寂静山林4 小时前
UVa 12991 Game Rooms
算法·1024程序员节
余俊晖5 小时前
RLVR训练多模态文档解析模型-olmOCR 2技术方案(模型、数据和代码均开源)
人工智能·算法·ocr·grpo
凉虾皮5 小时前
2024包河初中组
学习·算法·1024程序员节