-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathNumberOfProvinces.java
40 lines (32 loc) · 1.09 KB
/
NumberOfProvinces.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package disjointsets.problems;
import disjointsets.DisjointSet;
import utils.Reader;
import utils.Helper;
import java.io.IOException;
import java.util.HashSet;
// Leetcode Problem: https://leetcode.com/problems/number-of-provinces/
public class NumberOfProvinces {
public static void main (String[] args) throws IOException {
Reader reader = new Reader();
int n = reader.nextInt();
int[][] mat = Helper.getIntMatrix(n, reader);
NumberOfProvinces obj = new NumberOfProvinces();
System.out.println(obj.findCircleNum(mat));
}
public int findCircleNum(int[][] isConnected) {
int n = isConnected.length;
DisjointSet disjointset = new DisjointSet(n);
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
if (isConnected[i][j] == 1) {
disjointset.union(i, j);
}
}
}
HashSet<Integer> components = new HashSet<>();
for (int i=0; i<n; i++) {
components.add(disjointset.find(i));
}
return components.size();
}
}