原题链接在这里:https://leetcode.com/problems/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:

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

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

Example 2:

  1. 0 4
  2. | |
  3. 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.

题解:

使用一维UnionFind.

Time Complexity: O(elogn). e是edges数目. Find, O(logn). Union, O(1).

Space: O(n).

AC Java:

  1. class Solution {
  2. public int countComponents(int n, int[][] edges) {
  3. if(n <= 0){
  4. return 0;
  5. }
  6.  
  7. UnionFind uf = new UnionFind(n);
  8. for(int [] edge : edges){
  9. if(!uf.find(edge[0], edge[1])){
  10. uf.union(edge[0], edge[1]);
  11. }
  12. }
  13.  
  14. return uf.size();
  15. }
  16. }
  17.  
  18. class UnionFind{
  19. private int count;
  20. private int [] parent;
  21. private int [] size;
  22.  
  23. public UnionFind(int n){
  24. this.count = n;
  25. parent = new int[n];
  26. size = new int[n];
  27. for(int i = 0; i<n; i++){
  28. parent[i] = i;
  29. size[i] = 1;
  30. }
  31. }
  32.  
  33. public boolean find(int i, int j){
  34. return root(i) == root(j);
  35. }
  36.  
  37. private int root(int i){
  38. while(i != parent[i]){
  39. parent[i] = parent[parent[i]];
  40. i = parent[i];
  41. }
  42.  
  43. return parent[i];
  44. }
  45.  
  46. public void union(int i, int j){
  47. int rootI = root(i);
  48. int rootJ = root(j);
  49. if(size[rootI] > size[rootJ]){
  50. parent[rootJ] = rootI;
  51. size[rootI] += size[j];
  52. }else{
  53. parent[rootI] = rootJ;
  54. size[rootJ] += size[rootI];
  55. }
  56.  
  57. this.count--;
  58. }
  59.  
  60. public int size(){
  61. return this.count;
  62. }
  63. }

也可以使用BFS, DFS.

Time Complexity: O(n+e), 建graph用O(n+e), BFS, DFS 用 O(n+e). Space: O(n + e).

  1. public class Solution {
  2. public int countComponents(int n, int[][] edges) {
  3. List<List<Integer>> graph = new ArrayList<List<Integer>>();
  4. for(int i = 0; i<n; i++){
  5. graph.add(new ArrayList<Integer>());
  6. }
  7.  
  8. for(int [] edge : edges){
  9. graph.get(edge[0]).add(edge[1]);
  10. graph.get(edge[1]).add(edge[0]);
  11. }
  12.  
  13. HashSet<Integer> visited = new HashSet<Integer>();
  14. int count = 0;
  15. for(int i = 0; i<n; i++){
  16. if(!visited.contains(i)){
  17. // bfs(graph, i, visited);
  18. dfs(graph, i, visited);
  19. count++;
  20. }
  21. }
  22. return count;
  23. }
  24.  
  25. public void bfs(List<List<Integer>> graph, int i, HashSet<Integer> visited){
  26. LinkedList<Integer> que = new LinkedList<Integer>();
  27. visited.add(i);
  28. que.add(i);
  29. while(!que.isEmpty()){
  30. int cur = que.poll();
  31. List<Integer> neighbours = graph.get(cur);
  32. for(int neighbour : neighbours){
  33. if(!visited.contains(neighbour)){
  34. que.add(neighbour);
  35. visited.add(neighbour);
  36. }
  37. }
  38. }
  39. }
  40.  
  41. public void dfs(List<List<Integer>> graph, int i, HashSet<Integer> visited){
  42. visited.add(i);
  43. for(int neighbour : graph.get(i)){
  44. if(!visited.contains(neighbour)){
  45. dfs(graph, neighbour, visited);
  46. }
  47. }
  48. }
  49. }

跟上Find the Weak Connected Component in the Directed GraphNumber of Islands II.

LeetCode Number of Connected Components in an Undirected Graph的更多相关文章

  1. [LeetCode] 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), ...

  2. LeetCode 323. Number of Connected Components in an Undirected Graph

    原题链接在这里:https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ 题目: Giv ...

  3. [LeetCode] 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), ...

  4. 323. Number of Connected Components in an Undirected Graph (leetcode)

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

  5. Number of Connected Components in an Undirected Graph -- LeetCode

    Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), ...

  6. 【LeetCode】323. Number of Connected Components in an Undirected Graph 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 并查集 日期 题目地址:https://leetcod ...

  7. [Swift]LeetCode323. 无向图中的连通区域的个数 $ 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), ...

  8. [Locked] Number of Connected Components in an Undirected Graph

    Number of Connected Components in an Undirected Graph Given n nodes labeled from 0 to n - 1 and a li ...

  9. 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 n ...

随机推荐

  1. Web App开发入门

    WebApp与Native App有何区别呢? Native App: 1.开发成本非常大.一般使用的开发语言为JAVA.C++.Objective-C. 2.更新体验较差.同时也比较麻烦.每一次发布 ...

  2. Scheduled Projects

    Plans as at 10/03/15 ASB                                                             --------> Li ...

  3. exp.validate.js

    简单实用的js基础数据验证 prototype /// <reference path="/Scripts/expand-fn/exp_validate.js" /> ...

  4. 热烈祝贺华清远见《ARM处理器开发详解》第2版正式出版

    2014年6月,由华清远见研发中心组织多名业 内顶尖讲师编写的<ARM处理器开发详解>一书正式出版.本书以S5PV210处理器为平台,详细介绍了嵌入式系统开发的各个主要环节,并注重实践,辅 ...

  5. OO与设计模式的原则、目标

    OO与设计模式的原则.目标(转) 前两天,和一朋友聊到OO设计原则时,对设计模式有了更深的了解,在这里总结一下,与大家分享.OO(Object–Oriented )面向对象   OO方法(Object ...

  6. php在window下的环境配置(VC9)

    配置PHP5:  1. 配置PHP5.3.3,打开php安装目录(笔者是D:\php\php5)可以看到目录下有两个这样的文件php.ini-    development和php.ini-produ ...

  7. Update UI from an asynchronous thread

    One of the most common tasks you need to perform in a Windows Phone application is updating the UI f ...

  8. 一个网页抓取的类支持get+post+cookie存储

    前段时间提取了一个工具类,分享给大家: <?php class httpconnector { private $curl; private $cookie; private $kv; func ...

  9. scala 代码随笔

    def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = { var res = List[(T, T)]() var pre = iter.next ...

  10. HTML 5 服务器发送事件

    接收 Server-Sent 事件通知 EventSource 对象用于接收服务器发送事件通知: 实例 var source=new EventSource("demo_sse.php&qu ...