Skip to content

2316. Count Unreachable Pairs of Nodes in an Undirected Graph 👍

  • Time: $O(|V| + |E|)$
  • Space: $O(|V| + |E|)$
 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
class Solution {
 public:
  long long countPairs(int n, vector<vector<int>>& edges) {
    long ans = 0;
    vector<vector<int>> graph(n);
    vector<bool> seen(n);
    int unreached = n;

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      graph[u].push_back(v);
      graph[v].push_back(u);
    }

    for (int i = 0; i < n; ++i) {
      const int reached = dfs(graph, i, seen);
      unreached -= reached;
      ans += static_cast<long>(unreached) * reached;
    }
    return ans;
  }

 private:
  int dfs(const vector<vector<int>>& graph, int u, vector<bool>& seen) {
    if (seen[u])
      return 0;
    seen[u] = true;
    return accumulate(
        graph[u].begin(), graph[u].end(), 1,
        [&](int subtotal, int v) { return subtotal + dfs(graph, v, seen); });
  }
};
 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
class Solution {
  public long countPairs(int n, int[][] edges) {
    long ans = 0;
    List<Integer>[] graph = new List[n];
    boolean[] seen = new boolean[n];
    int unreached = n;

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      graph[u].add(v);
      graph[v].add(u);
    }

    for (int i = 0; i < n; ++i) {
      final int reached = dfs(graph, i, seen);
      unreached -= reached;
      ans += (long) unreached * reached;
    }
    return ans;
  }

  private int dfs(List<Integer>[] graph, int u, boolean[] seen) {
    if (seen[u])
      return 0;

    seen[u] = true;
    int ans = 1;
    for (final int v : graph[u])
      ans += dfs(graph, v, seen);
    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
  def countPairs(self, n: int, edges: list[list[int]]) -> int:
    ans = 0
    graph = [[] for _ in range(n)]
    seen = [0] * n
    unreached = n

    for u, v in edges:
      graph[u].append(v)
      graph[v].append(u)

    for i in range(n):
      reached = self._dfs(graph, i, seen)
      unreached -= reached
      ans += unreached * reached

    return ans

  def _dfs(self, graph: list[list[int]], u: int, seen: list[bool]) -> int:
    if seen[u]:
      return 0
    seen[u] = True
    return functools.reduce(lambda subtotal, v:
                            subtotal + self._dfs(graph, v, seen), graph[u], 1)