原题链接在这里: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:

     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.

题解:

使用一维UnionFind.

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

Space: O(n).

AC Java:

 class Solution {
public int countComponents(int n, int[][] edges) {
if(n <= 0){
return 0;
} UnionFind uf = new UnionFind(n);
for(int [] edge : edges){
if(!uf.find(edge[0], edge[1])){
uf.union(edge[0], edge[1]);
}
} return uf.size();
}
} class UnionFind{
private int count;
private int [] parent;
private int [] size; public UnionFind(int n){
this.count = n;
parent = new int[n];
size = new int[n];
for(int i = 0; i<n; i++){
parent[i] = i;
size[i] = 1;
}
} public boolean find(int i, int j){
return root(i) == root(j);
} private int root(int i){
while(i != parent[i]){
parent[i] = parent[parent[i]];
i = parent[i];
} return parent[i];
} public void union(int i, int j){
int rootI = root(i);
int rootJ = root(j);
if(size[rootI] > size[rootJ]){
parent[rootJ] = rootI;
size[rootI] += size[j];
}else{
parent[rootI] = rootJ;
size[rootJ] += size[rootI];
} this.count--;
} public int size(){
return this.count;
}
}

也可以使用BFS, DFS.

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

 public class Solution {
public int countComponents(int n, int[][] edges) {
List<List<Integer>> graph = new ArrayList<List<Integer>>();
for(int i = 0; i<n; i++){
graph.add(new ArrayList<Integer>());
} for(int [] edge : edges){
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
} HashSet<Integer> visited = new HashSet<Integer>();
int count = 0;
for(int i = 0; i<n; i++){
if(!visited.contains(i)){
// bfs(graph, i, visited);
dfs(graph, i, visited);
count++;
}
}
return count;
} public void bfs(List<List<Integer>> graph, int i, HashSet<Integer> visited){
LinkedList<Integer> que = new LinkedList<Integer>();
visited.add(i);
que.add(i);
while(!que.isEmpty()){
int cur = que.poll();
List<Integer> neighbours = graph.get(cur);
for(int neighbour : neighbours){
if(!visited.contains(neighbour)){
que.add(neighbour);
visited.add(neighbour);
}
}
}
} public void dfs(List<List<Integer>> graph, int i, HashSet<Integer> visited){
visited.add(i);
for(int neighbour : graph.get(i)){
if(!visited.contains(neighbour)){
dfs(graph, neighbour, visited);
}
}
}
}

跟上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. 163源报错Hash Sum mismatch 解决方法

    Ubuntu server 用的163的源,报错: W: Failed to fetch http://mirrors.163.com/ubuntu/dists/precise-updates/mai ...

  2. Redis内存缓存系统入门

    网站:http://redis.io/ key-value cache and store    data structure server 1. 服务器端 1.1 安装 下载安装包:http://r ...

  3. QWord2vec:word2vec移植版+GUI

    序 Word2Vec原生是不支持Windows的,索性就用Qt移植了一下. 大概做了下面几件事. ①替换LinuxAPI的pthread为QThread. ②取消了posix_memalign(),内 ...

  4. 20145308刘昊阳 《Java程序设计》第4周学习总结

    20145308刘昊阳 <Java程序设计>第4周学习总结 教材学习内容总结 第六章 继承与多态 6.1 何谓继承 继承:面向对象中,为避免多个类间重复定义共同行为使用 把相同代码提升为父 ...

  5. 洛谷 P1372 又是毕业季I Label:None

    题目背景 “叮铃铃铃”,随着高考最后一科结考铃声的敲响,三年青春时光顿时凝固于此刻.毕业的欣喜怎敌那离别的不舍,憧憬着未来仍毋忘逝去的歌.1000多个日夜的欢笑和泪水,全凝聚在毕业晚会上,相信,这一定 ...

  6. [Leetcode] Scramble String

    Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrin ...

  7. C#中的IComparable 和 IComparer 接口,实现列表中的对象比较和排序

    借豆瓣某博主的话先对这两个接口进行一个解释: IComparable在要比较的对象的类中实现,可以比较该对象和另一个对象 IComparer在一个单独的类中实现,可以比较任意两个对象. 如果已经支持 ...

  8. 创建需要计时器的windows service

    1.在VS中建立windows service后,应该添加一个安装程序. 2.在默认的Service1.cs设计界面右键,添加安装程序,生成ProjectInstaller.包含两个类serviceP ...

  9. 第1章 ZigBee协议栈初始化网络启动流程

    作者:宋老师,华清远见嵌入式学院讲师. ZigBee的基本流程:由协调器的组网(创建PAN ID),终端设备和路由设备发现网络以及加入网络. 基本流程:main()->osal_init_sys ...

  10. 20145330第十周《Java学习笔记》

    20145330第十周<Java学习笔记> 网络编程 网络编程就是在两个或两个以上的设备(例如计算机)之间传输数据.程序员所作的事情就是把数据发送到指定的位置,或者接收到指定的数据,这个就 ...