685. Redundant Connection II

来源:互联网 发布:淘宝拍卖车不可过户 编辑:程序博客网 时间:2024/05/16 17:48

In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.

The given input is a directed graph that started as a rooted tree with N nodes (with distinct values 1, 2, ..., N), with one additional directed edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.

The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] that represents a directed edge connecting nodes u and v, where u is a parent of child v.

Return an edge that can be removed so that the resulting graph is a rooted tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.

Example 1:

Input: [[1,2], [1,3], [2,3]]Output: [2,3]Explanation: The given directed graph will be like this:  1 / \v   v2-->3

Example 2:

Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]Output: [4,1]Explanation: The given directed graph will be like this:5 <- 1 -> 2     ^    |     |    v     4 <- 3

Note:

  • The size of the input 2D-array will be between 3 and 1000.
  • Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.


  • 思路:归纳有3种情况
     * 1. 有2个parent节点,无环
     * 2. 只有环
     * 3. 有2个parent节点,有环
     * 
     * 最开始想找到所有的candidate,然后注意去掉判断是否合法
     * 其实也可以直接就这样先求有没有2个parent的节点和有没有环


  • package l685;/* * 归纳有3种情况 * 1. 有2个parent节点,无环 * 2. 只有环 * 3. 有2个parent节点,有环 *  * 最开始想找到所有的candidate,然后注意去掉判断是否合法 * 其实也可以直接就这样先求有没有2个parent的节点和有没有环 */class Solution {    public int[] findRedundantDirectedConnection(int[][] edges) {    // 判断有么有2个parent节点    int[] in = new int[edges.length+4];    boolean has2parent = false;    int[] has2parentPos = new int[2];    for(int i=0; i<edges.length; i++) {    int[] t = edges[i];    in[t[1]]++;    if(in[t[1]] == 2) {    has2parent = true;    has2parentPos[1] = i;    for(int j=0; j<i; j++)    if(edges[j][1] == t[1]) {    has2parentPos[0] = j;    break;    }    break;    }    }        int[] ret = findRedundantConnection(edges, -1);        if(!has2parent)return ret;    if(ret == null)return edges[has2parentPos[1]];    if(findRedundantConnection(edges, has2parentPos[0])==null)    return edges[has2parentPos[0]];    else    return edges[has2parentPos[1]];    }    // 找有向图中的环    public int[] findRedundantConnection(int[][] edges, int p) {        int[]root = new int[edges.length+4];        for(int i=0; i<root.length; i++)root[i] = i;                for(int q=0; q<edges.length; q++) {        if(p == q)continue;        int i=edges[q][0], j=edges[q][1];                for(int k=0; k<root.length; k++) {if(root[k] == j)root[k] = root[i];}        if(root[i] == j)return edges[q];        }                return null;    }}