|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 2316. Count Unreachable Pairs of Nodes in an Undirected Graph |
| 4 | +# https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph |
| 5 | + |
| 6 | +=begin |
| 7 | +
|
| 8 | +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. |
| 9 | +
|
| 10 | +Return the number of pairs of different nodes that are unreachable from each other. |
| 11 | +
|
| 12 | +### Example 1: |
| 13 | +Input: n = 3, edges = [[0,1],[0,2],[1,2]] |
| 14 | +Output: 0 |
| 15 | +Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0. |
| 16 | +
|
| 17 | +### Example 2: |
| 18 | +Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]] |
| 19 | +Output: 14 |
| 20 | +Explanation: There are 14 pairs of nodes that are unreachable from each other: |
| 21 | +[[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]]. |
| 22 | +Therefore, we return 14. |
| 23 | +
|
| 24 | +### Constraints: |
| 25 | +* 1 <= n <= 105 |
| 26 | +* 0 <= edges.length <= 2 * 105 |
| 27 | +* edges[i].length == 2 |
| 28 | +* 0 <= ai, bi < n |
| 29 | +* ai != bi |
| 30 | +* There are no repeated edges. |
| 31 | +
|
| 32 | +=end |
| 33 | + |
| 34 | +# Runtime: 403 ms |
| 35 | +# Memory Usage: 247.1 MB |
| 36 | +# @param {Integer} n |
| 37 | +# @param {Integer[][]} edges |
| 38 | +# @return {Integer} |
| 39 | +def count_pairs(n, edges) |
| 40 | + @adj = Array.new(n + 1).map { [] } |
| 41 | + @v = Array.new(n + 1, false) |
| 42 | + @total = 0 |
| 43 | + @ans = 0 |
| 44 | + edges.each do |a, b| |
| 45 | + @adj[a].push(b) |
| 46 | + @adj[b].push(a) |
| 47 | + end |
| 48 | + (0...n).each do |i| |
| 49 | + next if @v[i] |
| 50 | + bfs(i) |
| 51 | + end |
| 52 | + @ans |
| 53 | +end |
| 54 | + |
| 55 | +def bfs(i) |
| 56 | + return if @v[i] |
| 57 | + count = 0 |
| 58 | + q = [i] |
| 59 | + @v[i] = true |
| 60 | + while !q.empty? |
| 61 | + x = q.shift |
| 62 | + count += 1 |
| 63 | + @ans += @total |
| 64 | + @adj[x].each do |j| |
| 65 | + next if @v[j] |
| 66 | + @v[j] = true |
| 67 | + q.push(j) |
| 68 | + end |
| 69 | + end |
| 70 | + @total += count |
| 71 | +end |
| 72 | + |
| 73 | +# **************** # |
| 74 | +# TEST # |
| 75 | +# **************** # |
| 76 | + |
| 77 | +require "test/unit" |
| 78 | +class Test_count_pairs < Test::Unit::TestCase |
| 79 | + def test_ |
| 80 | + assert_equal 0, count_pairs(3, [[0, 1], [0, 2], [1, 2]]) |
| 81 | + assert_equal 14, count_pairs(7, [[0, 2], [0, 5], [2, 4], [1, 6], [5, 4]]) |
| 82 | + end |
| 83 | +end |
0 commit comments