【LeetCode:2316. 统计无向图中无法互相到达点对数 | BFS + 乘法原理】-LMLPHP

【LeetCode:2316. 统计无向图中无法互相到达点对数 | BFS + 乘法原理】-LMLPHP

【LeetCode:2316. 统计无向图中无法互相到达点对数 | BFS + 乘法原理】-LMLPHP

🚩 题目链接

⛲ 题目描述

给你一个整数 n ,表示一张 无向图 中有 n 个节点,编号为 0 到 n - 1 。同时给你一个二维整数数组 edges ,其中 edges[i] = [ai, bi] 表示节点 ai 和 bi 之间有一条 无向 边。

请你返回 无法互相到达 的不同 点对数目 。

【LeetCode:2316. 统计无向图中无法互相到达点对数 | BFS + 乘法原理】-LMLPHP

【LeetCode:2316. 统计无向图中无法互相到达点对数 | BFS + 乘法原理】-LMLPHP

提示:

1 <= n <= 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ai, bi < n
ai != bi
不会有重复边。

🌟 求解思路&实现代码&运行结果


⚡ BFS+ 乘法原理

🥦 求解思路
  1. 题目让我们求解是从找到所有无法互相到达的不同点对数目,我们可以先找到每一个连通块的节点个数cnt,因为一共是n个节点,所以,剩下的不能到达的节点个数就是(n-cnt),所以,当前连通块中所有节点不能到达其它节点的个数是cnt * (n-cnt)-乘法原理。因为这只是一个连通块,其它情况类似,遍历下去,找到所有情况。
  2. 具体实现的时候,我们需要先建无向图,然后通过bfs求解,同时需要维护vis访问的节点的数组,避免重复访问。
  3. 最后,因为每个节点双向计算了两次。我们需要将结果/2来得到最终的结果。
  4. 具体求解的过程步骤请看下面代码。
🥦 实现代码
class Solution {
    public long countPairs(int n, int[][] edges) {
        long ans=0;
        ArrayList<Integer>[] list=new ArrayList[n]; 
        Arrays.setAll(list,e->new ArrayList<>());
        for(int[] edge:edges){
            int from=edge[0],to=edge[1];
            list[from].add(to);
            list[to].add(from);
        }
        Queue<Integer> queue=new LinkedList<>();
        boolean[] vis=new boolean[n];
        Arrays.fill(vis,false);
        for(int i=0;i<n;i++){
            if(!vis[i]){
                queue.add(i);
                vis[i]=true;
                int cnt=0;
                while(!queue.isEmpty()){
                    int size=queue.size();
                    for(int j=0;j<size;j++){
                        int cur=queue.poll();
                        cnt++;
                        for(int node:list[cur]){
                            if(!vis[node]){
                                queue.add(node);
                                vis[node]=true;
                            }
                        }
                    }
                }
                ans+=(long)(n-cnt)*cnt;
            }
        }
        return ans/2;
    }
}



🥦 运行结果

【LeetCode:2316. 统计无向图中无法互相到达点对数 | BFS + 乘法原理】-LMLPHP


💬 共勉

【LeetCode:2316. 统计无向图中无法互相到达点对数 | BFS + 乘法原理】-LMLPHP

【LeetCode:2316. 统计无向图中无法互相到达点对数 | BFS + 乘法原理】-LMLPHP

10-21 16:50