Count Unreachable Pairs of Nodes in an Undirected Graph Problem
Description
LeetCode Problem 2316.
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] = [a_i, b_i] denotes that there exists an undirected edge connecting nodes a_i and b_i.
Return the number of pairs of different nodes that are unreachable from each other.
Example 1:

Input: n = 3, edges = [[0,1],[0,2],[1,2]]
Output: 0
Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.
Example 2:

Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
Output: 14
Explanation: There are 14 pairs of nodes that are unreachable from each other:
[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].
Therefore, we return 14.
Constraints:
1 <= n <= 10^50 <= edges.length <= 2 * 10^5edges[i].length == 20 <= a_i, b_i < na_i != b_i- There are no repeated edges.
Solution
Approach: DFS over Components
Two nodes are reachable from each other exactly when they are in the same connected component, so every pair taken from different components is unreachable. Find the components with a DFS and their sizes. Keeping s, the number of nodes in the components seen so far, each new component of size t adds s * t unreachable pairs; then s += t.
Complexity: Time O(n + m), space O(n + m), where m is the number of edges.
class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
def dfs(i: int) -> int:
if vis[i]:
return 0
vis[i] = True
return 1 + sum(dfs(j) for j in g[i])
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
vis = [False] * n
ans = s = 0
for i in range(n):
t = dfs(i)
ans += s * t
s += t
return ans