Leetcode 6106、统计无向图中无法互相到达点对数

Leetcode 6106、统计无向图中无法互相到达点对数

Leetcode 6106、统计无向图中无法互相到达点对数_第1张图片

方法一、并查集

class Solution {
   
    public long countPairs(int n, int[][] edges) {
   
        Union union = new Union(n, edges);
        for(int[] edge : edges) {
   
            union.union(edge[0], edge[1]);
        }
        return union.getCount();
    }

    class Union{
   
        int[] parent;

        public Union(int n, int[][] edges) {
   
            parent = new int[n];
            for(int i = 0; i < n; i++) {
   
                parent[i] = i;
            }
        }

        public int find(int i) {
   
            if (parent[i] != i) parent[i] = find(parent[i]);
            return parent[i];
        }

        public void union(int x, int y) {
   
            int rootx = find(x);
            int rooty = find(y);
            if(rooty != rootx) {
   
                if(rootx >= rooty) {
   
                    parent[rooty] = rootx;
                }else{
   
                    parent[rootx] = rooty;
                }
            }
        }

        public long getCount() {
   
            long res = 0;
            Map<Integer,Integer> cnt = new 

你可能感兴趣的:(Leetcode题解,leetcode,算法,职场和发展)