LeetCode Interview Question 04.01. Path Between Nodes

Article directory

1. Title

  Paths between nodes. Given a directed graph, design an algorithm to find whether a path exists between two nodes.

  Click here to jump to the question .

Example 1:

Input: n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2 Output
: true

Example 2:

Input: 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
output: true

hint:

  • The number of nodes n is in the range [0, 10 5 ].
  • The node number is greater than or equal to 0 and less than n.
  • There may be self-loops and parallel edges in the graph.

2. C# problem solution

  Use the BFS method to find the path, the code is as follows:

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;
    }
}
  • Time complexity: O ( n + e ) O(n+e)O ( n+e ) ,eee is the number of edges of the directed graph.
  • Space Complexity: O ( n ) O(n)O ( n )

Guess you like

Origin blog.csdn.net/zheliku/article/details/132784345