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 }
  • 相关阅读:
    lnmp一键安装包,安装多版本php,并开启redis与swoole
    wangEditor的使用
    记一次傻逼的录入
    PHP自动加载
    pip升级
    Ubuntu安装mycli,让mysql命令行可以自动提示
    Redis存储AccessToken
    微信小程序生成太阳码
    巧妙的新订单提醒功能
    使用pt-query-digest进行日志分析
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6416655.html
Copyright © 2011-2022 走看看