-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js
More file actions
48 lines (43 loc) · 1.28 KB
/
2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.js
File metadata and controls
48 lines (43 loc) · 1.28 KB
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
/**
* 2316. Count Unreachable Pairs of Nodes in an Undirected Graph
* https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/
* Difficulty: Medium
*
* You are given an integer n. There is an undirected graph with n nodes, numbered from 0
* to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that
* there exists an undirected edge connecting nodes ai and bi.
*
* Return the number of pairs of different nodes that are unreachable from each other.
*/
/**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/
var countPairs = function(n, edges) {
const graph = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
}
const visited = new Array(n).fill(false);
let result = 0;
let totalNodes = 0;
for (let node = 0; node < n; node++) {
if (!visited[node]) {
const componentSize = exploreComponent(node);
result += totalNodes * componentSize;
totalNodes += componentSize;
}
}
return result;
function exploreComponent(node) {
if (visited[node]) return 0;
visited[node] = true;
let size = 1;
for (const neighbor of graph[node]) {
size += exploreComponent(neighbor);
}
return size;
}
};