LeetCode 面试题 04.01. 节点间通路

文章目录

一、题目

节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。

点击此处跳转题目

示例1:

输入: n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
输出: true

示例2:

输入: n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4
输出: true

提示:

  • 节点数量n在[0, 105]范围内。
  • 节点编号大于等于 0 小于 n。
  • 图中可能存在自环和平行边。

二、C# 题解

使用BFS方法寻找通路,代码如下:

csharp 复制代码
public class Solution {
    public bool FindWhetherExistsPath(int n, int[][] graph, int start, int target) {
        // 建立邻接表
        Dictionary<int, List<int>> dic = new Dictionary<int, List<int>>();
        for (int i = 0; i < graph.Length; i++) {
            int p = graph[i][0], q = graph[i][1];
            if (dic.ContainsKey(p) && !dic[p].Contains(q)) dic[p].Add(q);
            else dic[p] = new List<int> {q};
        }

        // BFS
        Queue<int> queue = new Queue<int>();
        queue.Enqueue(start);
        do {
            int node = queue.Dequeue();               // 取出结点
            if (node == target) return true;          // 判断是否为目标对象
            if (!dic.ContainsKey(node)) continue;     // 如果邻接表不存在该结点,则直接跳过
            for (int i = 0; i < dic[node].Count; i++) // 遍历邻接表,继续找后续节点
                queue.Enqueue(dic[node][i]);
            dic.Remove(node);                         // 访问过该结点,因此从邻接表中删除记录
        } while (queue.Count != 0);
        return false;
    }
}
  • 时间复杂度: O ( n + e ) O(n+e) O(n+e),其中 e e e 为有向图的边数。
  • 空间复杂度: O ( n ) O(n) O(n)。
相关推荐
用户47949283569159 小时前
"讲讲原型链" —— 面试官最爱问的 JavaScript 基础
前端·javascript·面试
用户47949283569159 小时前
2025 年 TC39 都在忙什么?Import Bytes、Iterator Chunking 来了
前端·javascript·面试
努力学算法的蒟蒻10 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
CoderYanger12 小时前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节
有时间要学习12 小时前
面试150——第二周
数据结构·算法·leetcode
测试199813 小时前
接口自动化测试套件封装示例详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
XUN4J15 小时前
深入解析MySQL事务与锁:构建高并发数据系统的基石
后端·面试
soda_yo15 小时前
浅拷贝与深拷贝: 克隆一只哈基米
前端·javascript·面试
用户66006766853916 小时前
从“养猫”看懂JS面向对象:原型链与Class本质拆解
前端·javascript·面试
小白程序员成长日记16 小时前
2025.12.03 力扣每日一题
算法·leetcode·职场和发展