-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path547_numberofprovinces.js
47 lines (42 loc) · 1.28 KB
/
547_numberofprovinces.js
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
41
42
43
44
45
46
47
/**
* @param {number[][]} isConnected
* @return {number}
*/
var findCircleNum = function(isConnected) {
let graph = new Map();
let nodesLen = isConnected.length;
// Create the hashmap
for(let i=0; i<nodesLen; i++) {
graph.set(i, []);
}
// add all the neighbors to the hashmap
for(let i=0; i<nodesLen; i++) {
// j = i+1 so that the same node is not added.
for(let j=i+1; j < nodesLen; j++) {
if(isConnected[i][j]) {
graph.get(i).push(j);
graph.get(j).push(i);
}
}
}
// create the seen array
let seen = new Array(nodesLen).fill(false);
let ans = 0; // number of provinces = number of hashes, each hash and their neighbors will form the connected component
for(let i=0; i< nodesLen; i++) {
if(!seen[i]) { // 1 to 2 has marked 2 as seen. hence 2 Must not calculate a province when hash takes it as a next node.
seen[i] = true;
ans++;
dfs(i);
}
}
function dfs(node) {
let neighbors = graph.get(node);
for(let each of neighbors) {
if(!seen[each]) {
seen[each] = true;
dfs(each);
}
}
}
return ans;
};