-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 684. Redundant Connection (#700)
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
class DisjointSet { | ||
private: | ||
vector<int> parent; | ||
public: | ||
DisjointSet(int n) { | ||
parent.resize(n+1); | ||
for (int i = 1; i < n + 1; ++i) { | ||
parent[i] = i; //initially all nodes are set as independent | ||
} | ||
} | ||
int find(int u) { | ||
if (parent[u] == u) return u; | ||
return parent[u] = find(parent[u]); | ||
} | ||
bool Union(int u, int v) { | ||
int parU = find(u); | ||
int parV = find(v); | ||
if (parU != parV) { // not part of the set yet | ||
parent[parV] = parU; | ||
return true; | ||
} else return false; // already part of the set | ||
|
||
} | ||
}; | ||
class Solution { | ||
public: | ||
vector<int> findRedundantConnection(vector<vector<int>>& edges) { | ||
int n = edges.size(); //here graphs with n nodes have n edges | ||
DisjointSet ds(n); | ||
for (const auto &edge : edges) { | ||
int u = edge[1], v = edge[0]; | ||
if (!ds.Union(u, v)) return edge; | ||
} | ||
return {}; | ||
} | ||
}; |