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)。
相关推荐
AlenTech9 小时前
238. 除了自身以外数组的乘积 - 力扣(LeetCode)
算法·leetcode·职场和发展
-KamMinG9 小时前
亲自面试版运维面试题(按需更新)
运维·面试·职场和发展
老鼠只爱大米9 小时前
LeetCode经典算法面试题 #41:缺失的第一个正数(位置交换法、标记法等多种方法详解)
算法·leetcode·原地哈希·缺失的第一个正数·算法面试·位图法·集合哈希法
百度搜不到…9 小时前
背包问题递推公式中的dp[j-nums[j]]到底怎么理解
算法·leetcode·动态规划·背包问题
一起养小猫10 小时前
LeetCode100天Day13-移除元素与多数元素
java·算法·leetcode
敲敲了个代码10 小时前
让 Vant 弹出层适配 Uniapp Webview 返回键
前端·javascript·vue.js·学习·面试·uni-app
YuTaoShao10 小时前
【LeetCode 每日一题】2943. 最大化网格图中正方形空洞的面积——(解法二)哈希集合
算法·leetcode·哈希算法
山顶夕景11 小时前
【BFS】两壶水倒出k升水
算法·leetcode·bfs·宽度优先
且去填词11 小时前
Go 内存分配器(TCMalloc):栈与堆的分配策略
开发语言·后端·面试·golang
踩坑记录11 小时前
leetcode hot100 41.第一个缺失的正数 hard
leetcode