zoukankan      html  css  js  c++  java
  • Number of Connected Components in an Undirected Graph -- LeetCode

    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.

    思路:并查集(Union find)

     1 class Solution {
     2 public:
     3     int getFather(vector<int>& father, int i) {
     4         if (father[i] == i) return i;
     5         father[i] = getFather(father, father[i]);
     6         return father[i];
     7     }
     8     void merge(vector<int>& father, int i, int j) {
     9         int fatherI = getFather(father, i);
    10         int fatherJ = getFather(father, j);
    11         father[fatherJ] = fatherI;
    12     }
    13     int countComponents(int n, vector<pair<int, int>>& edges) {
    14         vector<int> father;
    15         for (int i = 0; i < n; i++) father.push_back(i);
    16         for (int i = 0, n = edges.size(); i < n; i++)
    17             merge(father, get<0>(edges[i]), get<1>(edges[i]));
    18         unordered_set<int> unions;
    19         for (int i = 0; i < n; i++) unions.insert(getFather(father, i));
    20         return unions.size();
    21     }
    22 };
  • 相关阅读:
    MATLAB相机标定转XMl代码
    摄像头录制及调试
    opencv之常用还是忘,那咋办嘛
    Python贪吃蛇
    Linux指令
    寻找最小矩形边框--OpenCv
    2019 C语言测试
    opencv之重映射
    指针的总计
    图像变换之霍夫变换
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5786148.html
Copyright © 2011-2022 走看看