您的位置:首页 > 其它

LeetCode-Number of Connected Components in an Undirected Graph

2016-08-12 13:45 465 查看
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
.

Analysis:

From here: https://discuss.leetcode.com/topic/32752/easiest-2ms-java-solution
This is 1D version of Number of Islands II. For more explanations, check out this 2D Solution.

n
points =
n
islands =
n
trees =
n
roots.

With each edge added, check which island is
e[0]
or
e[1]
belonging to.

If
e[0]
and
e[1]
are in same islands, do nothing.

Otherwise, union two islands, and reduce islands count by
1
.

Bonus: path compression can reduce time by
50%
.

Hope it helps!

Solution:

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

int len = edges.length;
for (int i=0;i<len;i++){
int root1 = findRoot(roots,edges[i][0]);
int root2 = findRoot(roots,edges[i][1]);

if (root1!=root2){
roots[root1] = root2;
num--;
}
}

return num;
}

public int findRoot(int[] roots, int node){
while (roots[node]!=node){
roots[node] = roots[roots[node]];
node = roots[node];
}
return node;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: