Skip to content

Commit

Permalink
Merge pull request neetcode-gh#488 from hogo6002/patch-1
Browse files Browse the repository at this point in the history
Add JAVA solution for Question 323
  • Loading branch information
neetcode-gh authored Jul 15, 2022
2 parents e8fdc3d + 31cec75 commit 0e644d6
Showing 1 changed file with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
class Solution {
private int[] parent;
private int[] rank;

public int countComponents(int n, int[][] edges) {
parent = new int[n];
rank = new int[n];

for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 1;
}

int result = n;
for (int i = 0; i < edges.length; i++) {
if (union(edges[i][0], edges[i][1]) == 1) {
result--;
}
}

return result;
}

private int find(int node) {
int result = node;

while (parent[result] != result) {
parent[result] = parent[parent[result]];
result = parent[result];
}

return result;
}

private int union(int n1, int n2) {
int p1 = this.find(n1);
int p2 = this.find(n2);

if (p1 == p2) {
return 0;
}

if (rank[p2] > rank[p1]) {
parent[p1] = p2;
rank[p2] += rank[p1];
} else {
parent[p2] = p1;
rank[p1] += rank[p2];
}

return 1;
}
}

0 comments on commit 0e644d6

Please sign in to comment.