我直接给你 LeetCode 815 公交路线 的 Java 标准 BFS 解法,能直接提交 AC,思路清晰、注释完整。

题目大意

  • routes[i] :第  i  路公交车经过的所有车站
  • 你从  source  出发,到  target
  • 换乘一次算坐一辆新公交
  • 求最少要坐多少辆公交车才能到达

Java AC 代码

java

import java.util.*;

class Solution {
public int numBusesToDestination(int[][] routes, int source, int target) {
if (source == target) return 0;

    // 车站 -> 经过该车站的所有公交路线编号
    Map<Integer, List<Integer>> stopToBuses = new HashMap<>();
    for (int bus = 0; bus < routes.length; bus++) {
        for (int stop : routes[bus]) {
            stopToBuses.computeIfAbsent(stop, k -> new ArrayList<>()).add(bus);
        }
    }

    // 记录坐过的公交(避免重复坐)
    boolean[] visitedBus = new boolean[routes.length];
    Queue<Integer> q = new LinkedList<>();
    q.offer(source);

    int busCount = 0;

    while (!q.isEmpty()) {
        int size = q.size();
        busCount++; // 每一层 = 多坐一辆公交

        for (int i = 0; i < size; i++) {
            int curStop = q.poll();

            // 遍历当前车站能坐的所有公交
            for (int bus : stopToBuses.getOrDefault(curStop, Collections.emptyList())) {
                if (visitedBus[bus]) continue;
                visitedBus[bus] = true;

                // 遍历这辆公交所有站
                for (int stop : routes[bus]) {
                    if (stop == target) {
                        return busCount;
                    }
                    q.offer(stop);
                }
            }
        }
    }

    return -1;
}

}

核心思路(极简版)

1. 建图:每个车站 → 能坐哪些公交
2. BFS 按公交分层:

  • 每一层 = 多坐一辆公交
  • 访问过的公交直接标记,不再重复坐
    3. 第一次到达  target  时,当前层数就是最少公交数

关键点

  • 不是 BFS 车站,是 BFS 公交路线
  • 用  visitedBus  剪枝,效率极高
  • 时间复杂度:O(N + S),N=公交数,S=总车站数

如果你需要,我可以再给你:

  • 逐行手写讲解
  • 测试用例演示
  • 为什么不能用普通 BFS 的原因

需要吗?

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐