File tree 1 file changed +36
-0
lines changed
1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ class DisjointSet {
2
+ private:
3
+ vector<int> parent;
4
+ public:
5
+ DisjointSet(int n) {
6
+ parent.resize(n+1);
7
+ for (int i = 1; i < n + 1; ++i) {
8
+ parent[i] = i; //initially all nodes are set as independent
9
+ }
10
+ }
11
+ int find(int u) {
12
+ if (parent[u] == u) return u;
13
+ return parent[u] = find(parent[u]);
14
+ }
15
+ bool Union(int u, int v) {
16
+ int parU = find(u);
17
+ int parV = find(v);
18
+ if (parU != parV) { // not part of the set yet
19
+ parent[parV] = parU;
20
+ return true;
21
+ } else return false; // already part of the set
22
+
23
+ }
24
+ };
25
+ class Solution {
26
+ public:
27
+ vector<int> findRedundantConnection(vector<vector<int>>& edges) {
28
+ int n = edges.size(); //here graphs with n nodes have n edges
29
+ DisjointSet ds(n);
30
+ for (const auto &edge : edges) {
31
+ int u = edge[1], v = edge[0];
32
+ if (!ds.Union(u, v)) return edge;
33
+ }
34
+ return {};
35
+ }
36
+ };
You can’t perform that action at this time.
0 commit comments