Count Unreachable Pairs of Nodes in an Undirected Graph LeetCode solution in JavaScript

1
var countPairs = function (n, edges) {
2
const adj = [];
3

4
for (let i = 0; i < n; i++) {
5
adj.push([]);
6
}
7

8
for (let [from, to] of edges) {
9
adj[from].push(to);
10
adj[to].push(from);
11
}
12

13
const visited = new Set();
14

15
function dfs(from) {
16
visited.add(from);
17

18
let count = 1;
19

20
for (const to of adj[from]) {
21
if (!visited.has(to)) {
22
count += dfs(to);
23
}
24
}
25

26
return count;
27
}
28

29
const groups = [];
30

31
for (let i = 0; i < n; i++) {
32
if (!visited.has(i)) {
33
const count = dfs(i);
34
groups.push(count);
35
}
36
}
37

38
let ans = 0;
39

40
for (let i = 0; i < groups.length - 1; i++) {
41
for (let j = i + 1; j < groups.length; j++) {
42
ans += groups[i] * groups[j];
43
}
44
}
45

46
return ans;
47
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0