zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    第一章
    第一章 计算机系统漫游
    hihocoder #1014 : Trie树
    第一章
    来个小目标
    poj 1056 IMMEDIATE DECODABILITY
    poj 2001 Shortest Prefixes
    __name__ 指示模块应如何被加载
    Python 常用函数time.strftime()简介
    CentOS安装beEF做XSS平台
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6416655.html
Copyright © 2011-2022 走看看