Count Unreachable Pairs of Nodes in an Undirected Graph LeetCode solution in JavaScript
1var countPairs = function (n, edges) {2const adj = [];34for (let i = 0; i < n; i++) {5adj.push([]);6}78for (let [from, to] of edges) {9adj[from].push(to);10adj[to].push(from);11}1213const visited = new Set();1415function dfs(from) {16visited.add(from);1718let count = 1;1920for (const to of adj[from]) {21if (!visited.has(to)) {22count += dfs(to);23}24}2526return count;27}2829const groups = [];3031for (let i = 0; i < n; i++) {32if (!visited.has(i)) {33const count = dfs(i);34groups.push(count);35}36}3738let ans = 0;3940for (let i = 0; i < groups.length - 1; i++) {41for (let j = i + 1; j < groups.length; j++) {42ans += groups[i] * groups[j];43}44}4546return ans;47};