Skip to content

Commit 686a059

Browse files
authored
Merge pull request Sunchit#1052 from saorav21994/master-2
Create NumberOfProvinces.java
2 parents 6ecc8d3 + ba8fe5d commit 686a059

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// @saorav21994
2+
3+
class Solution {
4+
public int findCircleNum(int[][] isConnected) {
5+
6+
// k-connected component == number of islands
7+
8+
int r = isConnected.length;
9+
int c = r; // square matrix
10+
11+
Queue<Integer> queue = new LinkedList<>();
12+
int [] hash = new int[r];
13+
14+
int province = 0;
15+
16+
for (int i = 0; i < r; i++) {
17+
18+
if (hash[i] == 0) {
19+
20+
province += 1;
21+
22+
queue.offer(i);
23+
24+
while (!queue.isEmpty()) {
25+
int index = queue.poll();
26+
if (hash[index] != 1) {
27+
for (int j = 0; j < r; j++) {
28+
if (isConnected[index][j] == 1 && index != j) {
29+
queue.offer(j);
30+
}
31+
}
32+
}
33+
hash[index] = 1;
34+
}
35+
36+
}
37+
}
38+
39+
return province;
40+
41+
}
42+
}

0 commit comments

Comments
 (0)