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)。
相关推荐
某哈压力大24 分钟前
Vue的双向绑定与自定义组件的v-model
前端·面试
怕浪猫33 分钟前
GLM-5.4 深度拆解:750B 参数如何「循环」出 2-3T 级智能?
算法·面试·github
CoderYanger2 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第二弹):DispatcherServlet 源码分析+适配器模式
java·数据库·hive·spring boot·面试·java-ee·mybatis
Moment3 小时前
27B 的本地模型也能做知识图谱?太强了!😍😍😍
前端·后端·面试
我叫黑大帅15 小时前
换尺寸、转个角度就认不出同一张图?让 16×16 灰度网格做感知去重
后端·面试·php
Moment19 小时前
AI 写代码越来越快,程序员为什么反而更累了
前端·后端·面试
郝学胜-神的一滴20 小时前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger20 小时前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
Navigator_Z1 天前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
AIHR数智引擎1 天前
AI原生组织,转型的关键是体系化能力重构
人工智能·经验分享·职场和发展·重构·ai-native