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方法寻找通路,代码如下:

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蔗理苦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值