zoukankan      html  css  js  c++  java
  • [Locked] Number of Connected Components in an Undirected Graph

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

    分析:

      类似于图像处理中找到物体轮廓的泛洪算法。在本题中,每个点扫一遍,每条边扫一遍,点和边都不重复遍历,复杂度为O(V + E)

    代码:

    int number(int n, vector<pair<int, int> > edges) {
        //Store edges with hash map for efficient access
        unordered_multimap<int, int> hash;
        for(auto e : edges) {
            hash.insert(e);
            hash.insert(make_pair(e.second, e.first));
        }
        //Flood fill algorithm
        vector<bool> visited(n, false);
        int number = 0;
        for(int i = 0; i < n; i++) {
            if(!visited[i]) {
                number++;
                visited[i] = true;
                queue<int> myq;
                myq.push(i);
                while(!myq.empty()) {
                    auto range = hash.equal_range(myq.front());
                    myq.pop();
                    auto pos = range.first;
                    while(pos != range.second) {
                        if(!visited[pos->second]) {
                            myq.push(pos->second);
                            visited[pos->second] = true;
                        }
                        pos++;
                    }
                }
            }
        }
        return number;
    }
  • 相关阅读:
    直接插入排序
    希尔排序
    堆排序
    红黑树
    hashMap原理
    JAVA随笔4
    JAVA随笔3(集合框架,流)
    Linux环境下如何生成core文件
    Centos6 升级glibc-2.17,解决Requires: libc.so.6(GLIBC_2.14)(64bit)错误解决方法
    MediaWiki搭建步骤
  • 原文地址:https://www.cnblogs.com/littletail/p/5202079.html
Copyright © 2011-2022 走看看