-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
50 lines (46 loc) · 1.27 KB
/
main.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
48
49
50
// URL: https://leetcode.com/problems/number-of-provinces/
/**
* @param {number[][]} isConnected
* @return {number}
*/
var findCircleNum = function (isConnected) {
const config = {};
let firstKey = null;
for (let index = 0; index < isConnected.length; index++) {
for (
let childIndex = 0;
childIndex < isConnected[index].length;
childIndex++
) {
if (index !== childIndex && isConnected[index][childIndex]) {
if (!config[index]) {
if (firstKey === null) {
firstKey = index;
}
config[index] = [];
}
config[index].push(childIndex);
}
}
}
let count = 0;
const encounteredKeys = {};
function explore(key) {
if (encounteredKeys[key]) {
return;
}
encounteredKeys[key] = true;
if (config[key] && config[key].length) {
for (const key1 of config[key]) {
explore(key1);
}
}
}
for (let index = 0; index < isConnected.length; index++) {
if (!encounteredKeys[index]) {
count++;
explore(index);
}
}
return count;
};