Tuesday, March 14, 2017

[LintCode] 591 Connecting Graph III 解题报告

Description
Given n nodes in a graph labeled from 1 to n. There is no edges in the graph at beginning.

You need to support the following method:
1. connect(a, b), add an edge to connect node a and node b.
2. query(), Returns the number of connected component in the graph


Example
5 // n = 5
query() return 5
connect(1, 2)
query() return 4
connect(2, 4)
query() return 3
connect(1, 4)
query() return 3


思路
implement一下Union Find。
初始一共有n个component。每次union,如果发现需要连到一起了,那么component就减少了一个。最后搞完就是剩下有多少个connected component。


Code
public class ConnectingGraph3 {

    private int numComponent;
    private int[] id;
    
    public int find(int i) {
        while (i != id[i]) {
            id[i] = id[id[i]];
            i = id[i];
        }
        return i;
    }
    
    public int getComponent() {
        return numComponent;
    }
    
    public ConnectingGraph3(int n) {
        // initialize your data structure here.
        
        numComponent = n;
        id = new int[n + 1];
        for (int i = 0; i < n + 1; i++) {
            id[i] = i;
        }
    }

    public void connect(int a, int b) {
        // Write your code here
        
        int i = find(a);
        int j = find(b);
        if (i != j) {
            id[i] = j;
            numComponent--;
        }
    }
        
    public int query() {
        // Write your code here
        
        return getComponent();
    }
}