Number of Connected Component 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.

 

 1 public class Solution {
 2     public int countComponents(int n, int[][] edges) {
 3         int[] parent = new int[n];
 4         for (int i = 0; i < n; i++)
 5             parent[i] = i;
 6             
 7         int result = n;
 8         for (int[] edge : edges) {
 9             int start = updateParent(parent, edge[0]);
10             int end = updateParent(parent, edge[1]);
11             
12             if (start != end) {
13                 parent[end] = start;
14                 result--;
15             }
16         }
17         return result;
18     }
19     
20     private int updateParent(int[] parent, int index) {
21         while (parent[index] != index) {
22             parent[index] = parent[parent[index]];
23             index = parent[index];
24         }
25         return index;
26     }
27     
28 }

 

posted @ 2017-02-19 19:17  amazingzoe  阅读(175)  评论(0编辑  收藏  举报