589. 連接圖

描述

給一個(gè)圖中的n個(gè)節(jié)點(diǎn), 記為 1 到 n . 在開始的時(shí)候圖中沒有邊。
你需要完成下面兩個(gè)方法:

  1. connect(a, b), 添加連接節(jié)點(diǎn) a, b 的邊.
  2. query(a, b), 檢驗(yàn)兩個(gè)節(jié)點(diǎn)是否聯(lián)通

樣例

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

代碼

public class ConnectingGraph { 

    private int[] father = null;

    private int find(int x) {
        if (father[x] == x) {
            return x;
        }
        return father[x] = find(father[x]);
    }
 
    // 初始化時(shí)父結(jié)點(diǎn)都是自己
    public ConnectingGraph(int n) {
        // initialize your data structure here.
        father = new int[n + 1];
        for (int i = 1; i <= n; ++i)
            father[i] = i;
    }

    // 連接兩結(jié)點(diǎn)即為并查集合并操作
    public void connect(int a, int b) {
        int root_a = find(a);
        int root_b = find(b);
        if (root_a != root_b)
            father[root_a] = root_b;
    }
        
    // 查詢兩結(jié)點(diǎn)是否相連,即為并查集查詢兩結(jié)點(diǎn)是否擁有相同父結(jié)點(diǎn)
    public boolean  query(int a, int b) {
        int root_a = find(a);
        int root_b = find(b);
        return root_a == root_b;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容