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)。
相关推荐
晨米酱4 天前
AGENTS.md:Agent 的上下文策略层
面试·架构·agent
旖旎夜光4 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
彧azz4 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
CoderYanger4 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂4 天前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
爱学习的执念4 天前
助力金九银十1000道软件测试面试题(功能、接口、自动化、WEB、APP.......)附答案
软件测试·面试
小的~~4 天前
银河麒麟V10 ARM部署TDengine(涛思)工业时序数据库安装与测试
面试·程序员创富
Tim_104 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
2401_832298104 天前
人机协同:AI时代全新工作与学习范式
职场和发展
童园管理札记4 天前
从政策驱动到课堂落地:2026年“人工智能+教育”全景解读与技术实践指南
人工智能·python·深度学习·职场和发展·学习方法