Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions 684. Redundant Connection
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 {};
}
};
Loading