323. Number of Connected Components in an Undirected Graph

May-26-2019

UF做算是白给的
压缩下,没Quick union(否则要几把weight),然后比较integer用equals稳点= =顺便尽量别int[]能MAP最好MAP

class Solution {
    
    public class UF {
        Map<Integer, Integer> roots;
        Map<Integer, Integer> size;
        int num;
        public UF(int n) {
            roots = new HashMap<>();
            size = new HashMap<>();
            num = n;
            for (int i = 0; i < n; i ++) {
                roots.put(i, i);
                size.put(i, 1);
            }
        }
        
        public Integer find(Integer n) {
            if (!roots.containsKey(n)) return null;
            Integer root = n;
            while (!root.equals(roots.get(root))) {
                roots.put(root, roots.get(roots.get(root)));
                root = roots.get(root);
            }
            return root;
        }
        
        public void union(Integer a, Integer b) {
            Integer rootA = find(a);
            Integer rootB = find(b);
            
            if (rootA == null || rootB == null || rootA.equals(rootB)) return;
            
            Integer sizeA = size.get(rootA);
            Integer sizeB = size.get(rootB);
            if (sizeA > sizeB) {
                roots.put(rootB, rootA);
                size.put(rootA, sizeB + sizeA);
            } else {
                roots.put(rootA, rootB);
                size.put(rootB, sizeA + sizeB);
            }
            this.num --;
        }
        
    }
    public int countComponents(int n, int[][] edges) {
        if (edges.length == 0 || edges[0].length == 0) return n;
        
        UF uf = new UF(n);
        for (int[] edge : edges) {
            Integer a = edge[0];
            Integer b = edge[1];
            uf.union(a, b);
        }
        return uf.num;
    }
}
原文地址:https://www.cnblogs.com/reboot329/p/5947859.html