323. Number of Connected Components in an Undirected Graph (leetcode)

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.

Example 1:

Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]]

     0          3
     |          |
     1 --- 2    4 

Output: 2

Example 2:

Input: n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]]

     0           4
     |           |
     1 --- 2 --- 3

Output:  1

Note:
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

idea: //use union find and count

class Solution {
    class UnionFind{
        HashMap<Integer,Integer> map = new HashMap<>();
        HashMap<Integer,Integer> sz = new HashMap<>();
        int count;//num of component
        UnionFind(int n){
            count = n;//?
            for(int i = 0; i<n; i++){
                map.put(i, i);
                sz.put(i, 1);
            }
        }
        Integer root(int p){
            if(!map.containsKey(p)) return null;
            while(p != map.get(p)){
                Integer temp = map.get(map.get((p)));
                map.put(p, temp);
                p = map.get(p);
            }
            return p;
        } 
        void Union(int p, int q){
            Integer pid =  root(p);
            Integer qid = root(q);
            if(pid == null || qid == null) return;
            if(pid.equals(qid) ) return;
            
            if(sz.get(pid) > sz.get(qid) ){
                map.put(qid, pid);
                sz.put(pid, sz.get(pid)+sz.get(qid));
            }else {
                map.put(pid, qid);
                sz.put(qid, sz.get(pid)+sz.get(qid));
            }
            count--;
        }
    }
    public int countComponents(int n, int[][] edges) {
        UnionFind uf = new UnionFind(n);
        for(int i = 0; i<edges.length; i++){
            uf.Union(edges[i][0], edges[i][1]);
        }
        return uf.count;
    }
}

 

posted @ 2018-05-23 13:25  wz30  阅读(128)  评论(0编辑  收藏  举报