Created
May 31, 2023 14:10
-
-
Save Desolve/26aa057a36ea78c2d4511cba41333eeb to your computer and use it in GitHub Desktop.
0547 Number of Provinces
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
import java.util.*; | |
class Solution { | |
private int[] root; | |
private int[] rank; | |
public int findCircleNum(int[][] edges) { | |
int n = edges.length; | |
root = new int[n]; | |
rank = new int[n]; | |
Arrays.fill(rank, 1); | |
for (int i = 0; i < n; i++) | |
root[i] = i; | |
for (int i = 0; i < n; i++) | |
for (int j = i + 1; j < n; j++) | |
if (edges[i][j] == 1) | |
union(i, j); | |
Set<Integer> res = new HashSet<>(); | |
for (int i = 0; i < n; i++) | |
res.add(find(i)); | |
return res.size(); | |
} | |
private int find(int i) { | |
int r = root[i]; | |
while (r != root[r]) { | |
root[r] = root[root[r]]; | |
r = root[r]; | |
} | |
root[i] = r; | |
return r; | |
} | |
private void union(int x, int y) { | |
int rx = find(x); | |
int ry = find(y); | |
if (rx == ry) { | |
return; | |
} | |
if (rank[rx] >= rank[ry]) { | |
rank[rx] += rank[ry]; | |
root[ry] = rx; | |
} else { | |
rank[ry] += rank[rx]; | |
root[rx] = ry; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment