589.Connecting Graph

1.Description(Medium)

Givennnodes in a graph labeled from1ton. 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 nodeaand node b. 2.query(a, b)`, check if two nodes are connected

Example

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

Tags

Union Find

2.Code

public class ConnectingGraph { 

    public ConnectingGraph(int n) {
        // initialize your data structure here.
    }

    public void connect(int a, int b) {
        // Write your code here
    }

    public boolean  query(int a, int b) {
        // Write your code here
    }
}

经典的实现union find

http://blog.csdn.net/dm_vincent/article/details/7655764

可以采用parent-link的方式将节点组织起来,举例而言,id[p]的值就是p节点的父节点的序号,

如果p是树根的话,id[p]的值就是p,因此最后经过若干次查找,一个节点总是能够找到它的根节点,即满足id[root] = root的节点也就是组的根节点了,

然后就可以使用根节点的序号来表示组号。

所以在处理一个pair的时候,将首先找到pair中每一个节点的组号(即它们所在树的根节点的序号),

如果属于不同的组的话,就将其中一个根节点的父节点设置为另外一个根节点,相当于将一颗独立的树编程另一颗独立的树的子树。

Last updated

Was this helpful?