[LeetCode] Redundant Connection II

685. Redundant Connection II

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 from 1 to 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 [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent of child vi.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
unordered_map<int, vector<int>> parent;
unordered_map<int, int> graph;
bool hasCycle(int start, int target) {
while(parent.count(start)) {
start = parent[start][0];
if(start == target) return true;
}
return false;
}
int find(int n) {
if(!graph.count(n)) {
return graph[n] = n;
} else return graph[n] == n ? n : graph[n] = find(graph[n]);
}
public:
vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
int targetNode = INT_MIN;
vector<int> res;
for(auto vec : edges) {
parent[vec[1]].push_back(vec[0]);
if(parent[vec[1]].size() == 2) targetNode = vec[1];

int pa = find(vec[0]), pb = find(vec[1]);
if(pa == pb) {
res = vec;
} else graph[pa] = graph[pb] = min(pa,pb);

}
if(targetNode == INT_MIN) return res;
if(hasCycle(parent[targetNode][0], targetNode)) {
return {parent[targetNode][0], targetNode};
} else {
return {parent[targetNode][1], targetNode};
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/17/PS/LeetCode/redundant-connection-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.