Question 6 Redundant Connection II

有向图还有可能因为没有环,但是有些有两个爸爸导致不合法

Method 1: DFS

  • 有向图的root是谁呢?

    • tree里根节点是唯一的一个没有爸爸的点, indegree of root为0有没有可能找不到root,如果不存在入度为2的点呢?

  • Question:有没有可能找不到root:如果不存在入度为2的点呢?(need复习)

  • 不合法的情况到底有几种

    • every node has only one parent, and there is a Cycle that include the root node (cycle edge)

    • there is a node with two parents but no cycle (two-parent edge)

    • there is a node with two parents; also, there is a cycle! (环上最后一条边)

有向图找环

  • 如果有环,那就从环上的点出发,找到环上的最后一条边

  • 如果没有环,有个一点有两个parent

Method 2

思路分析, Three case:

  • Every node has only one parent, and there is a cycle which include root node

  • There is a node with two parents, no cycle

  • There is a node with two parents, and a cycle

Union 的过程中要能去区分:indegree = 2 的结果啊,还是环的结果呢?

Union(a,b)的时候,

  • 如果alaoda = blaoda没问题,cycle造成的结果

  • 如果alaoda != blaoda: 有没有可能是个possibleResult呢?

区别是什么?

  • union(a,b)的时候b的老大是谁,因为我们union的顺序是b加入a的话,b的老大是不是自己

为什么一定要遍历找result而不是直接return result1 和result2

Last updated