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)。
相关推荐
江湖十年4 小时前
Go 并发控制:sync.Pool 详解
后端·面试·go
rainbow7242444 小时前
AI人才简历评估选型:技术面试、代码评审与项目复盘的综合运用方案
人工智能·面试·职场和发展
张张123y4 小时前
RAG从0到1学习:技术架构、项目实践与面试指南
人工智能·python·学习·面试·架构·langchain·transformer
一叶落4385 小时前
题目:15. 三数之和
c语言·数据结构·算法·leetcode
努力学算法的蒟蒻5 小时前
day115(3.17)——leetcode面试经典150
面试·职场和发展
Baihai_IDP6 小时前
OpenClaw 架构详解 · 第一部分:控制平面、会话管理与事件循环
人工智能·面试·llm
big_rabbit05026 小时前
[算法][力扣222]完全二叉树的节点个数
数据结构·算法·leetcode
张李浩7 小时前
Leetcode 15三题之和
算法·leetcode·职场和发展
x_xbx8 小时前
LeetCode:206. 反转链表
算法·leetcode·链表
abant28 小时前
leetcode 138 复制随机链表
算法·leetcode·链表