LC-323 Number of Connected Components in an Undirected Graph

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:

     0          3
     |          |
     1 --- 2    4

Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], return 2.

Example 2:

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

Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]], return 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.

public class Solution {
    public int countComponents(int n, int[][] edges) {
        Map<Integer, Integer> roots = new HashMap<>();
        
        for (int i = 0; i < n; i++) {
            roots.put(i, i);
        }
        
        int islands = n;
        for (int i = 0; i < edges.length; i++) {
            int root1 = find(roots, edges[i][0]);
            int root2 = find(roots, edges[i][1]);
            if (root1 != root2) {
                //union root2 into root1
                roots.put(root2, root1);
                islands--;
            }
        }
        return islands;
    }
    
    public int find(Map<Integer, Integer> roots, int id) {
        while (roots.get(id) != id) {
            //change father to grandfather
            roots.put(id, roots.get(roots.get(id))); //path compression
            id = roots.get(id);
        }
        
        return id;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • 受傷后反思 全局考慮 不在一人 不圖一時快意
    粒粒昂閱讀 262評論 0 0
  • 事情起源于元旦當(dāng)天,幾個同學(xué)說好了要聚在一起吃個飯,熱鬧一下,突然L小姐說男朋友的父母要過來就不來了。本想挺難得的...
    神盾局副局長閱讀 255評論 0 0
  • 《現(xiàn)代漢語詞典》對文化的解釋是:人類在社會歷史發(fā)展過程中所創(chuàng)造的物質(zhì)財富和精神財富的總和。 如果按照這個定義來理解...
    胡鈞閱讀 356評論 0 1
  • 在PCH中宏定義
    HAKA閱讀 299評論 0 0
  • 七夕快樂! 5年后,我希望我可以遇到一個在我身邊陪我走過難關(guān)的人! 我的七夕節(jié)愿望實現(xiàn)了,嘿嘿,終于等到它,還好沒...
    emYa閱讀 228評論 0 0

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