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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 受伤后反思 全局考虑 不在一人 不图一时快意
    粒粒昂阅读 1,534评论 0 0
  • 事情起源于元旦当天,几个同学说好了要聚在一起吃个饭,热闹一下,突然L小姐说男朋友的父母要过来就不来了。本想挺难得的...
    神盾局副局长阅读 1,625评论 0 0
  • 《现代汉语词典》对文化的解释是:人类在社会历史发展过程中所创造的物质财富和精神财富的总和。 如果按照这个定义来理解...
    胡钧阅读 2,515评论 0 1
  • 在PCH中宏定义
    HAKA阅读 1,839评论 0 0
  • 七夕快乐! 5年后,我希望我可以遇到一个在我身边陪我走过难关的人! 我的七夕节愿望实现了,嘿嘿,终于等到它,还好没...
    emYa阅读 1,313评论 0 0