685. Redundant Connection II

685

.

In this problem, a rooted tree is adirectedgraph 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 ofedges. Each element ofedgesis a pair[u, v]that represents adirectededge connecting nodesuandv, whereuis a parent of childv.

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   v
2--
>
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.Redundant Connection II

class Solution {

    public int[] findRedundantDirectedConnection(int[][] edges) {
        int n = edges.length, count = 0; // Use count to track the number of the invalid edge.

        int[] roots = new int[n + 1];

        int[] res = new int[2];

        for (int i = 0; i <= n ; i++) roots[i] = i;

        for (int i = 0; i < n; i++) {
            int parent = edges[i][0], child = edges[i][1];

            if (roots[child] != child || find(roots, parent) == child) {res = edges[i]; count++;}

            else roots[child] = parent;
        }

        if (count == 1) return res; // If there's only one invalid edge, return this edge.

        // Reset and do it the reverse way.
        for (int i = 0; i <= n ; i++) roots[i] = i; 

        for (int i = n - 1; i >= 0; i--) {
            int parent = edges[i][0], child = edges[i][1];

            if (roots[child] != child || find(roots, parent) == child) return edges[i];

            roots[child] = parent;
        }

        return res;
    }

    private int find(int[] roots, int x) {
        if (roots[x] == x) return x;

        return find(roots, roots[x]);
    }
}

results for ""

    No results matching ""