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.

一刷
题解:union and find
在find的过程中compress可以减小树的深度,加快速度

class Solution {
    public int countComponents(int n, int[][] edges) {
        int[] roots = new int[n];
        for(int i=0; i<n; i++){
            roots[i] = i;
        }
        
        for(int[] edge : edges){
            int rootA = find(edge[0], roots);
            int rootB = find(edge[1], roots);
            if(rootA != rootB){
                roots[rootA] = rootB;
                n--;
            }
        }
        return n;
    }
    
    private int find(int node, int[] roots){
        while(node!=roots[node]){
            roots[node] = roots[roots[node]];//compression
            node = roots[node];
        }
        return node;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容