博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Number of Connected Components in an Undirected Graph
阅读量:6292 次
发布时间:2019-06-22

本文共 1223 字,大约阅读时间需要 4 分钟。

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

Use Union Find to figure out the number of connected components

1 public class Solution { 2     public int countComponents(int n, int[][] edges) { 3         unionFind uf = new unionFind(n); 4         for (int[] edge : edges) { 5             if (!uf.isConnected(edge[0], edge[1])) { 6                 uf.union(edge[0], edge[1]); 7             } 8         } 9         return uf.findCount();10     }11     12     public class unionFind{13             int[] ids;14             int count;15             16             public unionFind(int num) {17                 this.ids = new int[num];18                 for (int i=0; i

 

转载地址:http://qjcta.baihongyu.com/

你可能感兴趣的文章
[转]程序集之GAC---Global Assembly Cache
查看>>
英语词汇(5)followed by / sung by / written by
查看>>
HDFS Namenode启动过程
查看>>
SQL Server查询某个字段存在哪些表中
查看>>
web实现QQ第三方登录 开放平台-web实现QQ第三方登录
查看>>
【划分树+二分】HDU 4417 Super Mario
查看>>
WPF 基础到企业应用系列1——开篇故意
查看>>
Android - TextureView, SurfaceView和GLSurfaceView 以及 SurfaceTexture
查看>>
【GoldenGate】使用OGG,两个Oracle库之间单向同步数据
查看>>
Jenkins构建完成后通过SVN Publisher Plugin上传文件到指定的SVN(教程收集)
查看>>
10-01 Java 类,抽象类,接口的综合小练习--运动员和教练
查看>>
一级域名和二级域名的区别是什么?作用怎样?
查看>>
Jedis连接redis
查看>>
在windows下安装python包管理器pip及使用
查看>>
CSS属性选择器和部分伪类
查看>>
JAVA正則表達式小总结
查看>>
BEGINNING SHAREPOINT® 2013 DEVELOPMENT 第12章节--SP 2013中远程Event Receivers 总结
查看>>
母亲与背影
查看>>
pasty公式
查看>>
jmeter使用beanshell构造参数化
查看>>