您的位置:首页 > 其它

Leetcode 323. Number of Connected Components in an Undirected Graph

2016-10-01 15:07 447 查看


323. Number of Connected Components in an Undirected Graph 

Total Accepted: 13742 Total Submissions: 30534 Difficulty: Medium

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
.

Hide Company Tags
 Google Twitter

Hide Tags
 Depth-first Search Breadth-first
Search Union Find Graph

Hide Similar Problems
 (M) Number of Islands (M)
Graph Valid Tree

思路:

通过今晚的两道题 + debug 算是union find学的差不多了。

首先上代码:

public class Solution {
public int countComponents(int n, int[][] edges) {
int[] id = new int
;
for(int i = 0; i < n; i++) id[i] = i;

for(int[] item : edges){
id[find(id, item[1])] = find(id, item[0]);
}

Set<Integer> set = new HashSet<>();
for(int i = 0; i < n; i++) set.add(find(id, i));
return set.size();
}

public int find(int[] id, int pos){
if(id[pos] == pos) return pos;
id[pos] = find(id, id[pos]);
return id[pos];
}
}

有两个很重要的点:


1. 为什么是set.add(find(id, i)) 而不是set.add(id[i])

例子:

4

[[0,1],[2,3],[1,2]]

首先[0, 1] 输入之后:0 0 2 3

然后[2, 3] 输入之后:0 0 2 2 (如果赋值代码左右反过来是 1 1 3 3)。

然后[1, 2] 输入之后:0 2 2 2。

如果直接加set会直接输出2(两个连通分量)。事实是0连着1,1连着2。只有1个。因此要在输出的时候再次调用find函数递归更新一下0的id到根节点2。

2. 为什么是id[find(id, item[1])] = find(id, item[0]) 而不是id[item[1]] = find(id, item[0]) 

例子:

3

[[1,0],[2,0]]

首先[1, 0] 之后得到1 1 2

然后[2, 0] 之后得到2 1 2

这样无论你在set.add的时候再次调用find(id, 0)去更新0的id也于事无补。why ? 因为0挂在1下面,应该把1开始整个挂在2下面而不是仅仅移动0。id[0]只移动了一个元素。而find(0)先找到了其根1,这样修改的时候改了根;之后通过set.add时候调用find(0)就能找到1的根2并更新。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息