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, 10^5^范围内。
  • 节点编号大于等于 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)。
相关推荐
wy_hhxx13 小时前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
AIgorithmGEEK15 小时前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
Navigator_Z18 小时前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
Baihai_IDP19 小时前
便宜又好用的模型,为什么越来越集中在闭源阵营?
人工智能·面试·llm
Rain的Java大神之路20 小时前
大四 Java 校招速成路线:从高频八股到可部署项目,30 天、8 周、12 周都能照着练
java·后端·面试
李剑一20 小时前
框架迭代的其实很快,但找工作的时候才发现,根本没有用新技术的公司
面试
怕浪猫1 天前
NVIDIA 全产品谱系与演进
javascript·面试·github
我叫黑大帅1 天前
拒绝加字段堆屎山!利用位掩码与流程编排优雅落地 上图下文 复合状态
后端·算法·面试
Cosolar1 天前
监控指标全正常,订单接口从 80ms 涨到 4s 故障复盘
java·后端·面试
Navigator_Z1 天前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode