【问题标题】:Finding number of connected components in an undirected graph在无向图中查找连通分量的数量
【发布时间】:2016-02-19 17:40:13
【问题描述】:

用户输入顶点的数量 (n),然后 - 在接下来的 n 行中 - 顶点是如何连接的,即数量 x第 i 行中的 表示顶点 i 与顶点 x 相连(图是无向的)。任务是在此图中找到连接组件的数量,而我的代码 - 由于某种原因我无法找到 - 输出错误值(例如,输入 4 2 1 2 4 ,我的代码输出 4 而不是 2)。非常感谢任何帮助。

#include <iostream>
#include <vector>
#include <stack>

int n;

using namespace std;
vector <int> graph[1000006];
int components[1000006];
int no_of_components;
stack <int> mystack;

int main(){

    cin >> n;

    for (int i=0; i<n; i++){
        int X;
        cin >> X;
        graph[X-1].push_back(i);
    }

    for (int i=0; i<n; i++){

        if (components[i]>0) continue;

        no_of_components++;

        mystack.push(i);
        components[i]=no_of_components;

        while (mystack.empty()==false){
            int v;

            v=mystack.top();
            mystack.pop();

            for (int u=0; u<graph[v].size(); u++){
                if (components[u]>0) continue;

                mystack.push(u);
                components[u]=no_of_components;

            }
        }
    }

    cout << no_of_components;

    return 0;

}

【问题讨论】:

    标签: c++ graph depth-first-search connected-components


    【解决方案1】:

    在您的代码中,计数器 u 允许您遍历节点 v 的连接与连接本身之间存在混淆:

    • v 是一个节点
    • graph[v] 是连接向量
    • u 是连接向量中的索引
    • 所以graph[v][u] 是连接到v 的节点,component[graph[v][u]] 是您必须更新的组件标记

    所以你必须纠正内部for循环如下:

            for (int u=0; u<graph[v].size(); u++){
                if (components[graph[v][u]]>0) continue;
    
                mystack.push(graph[v][u]);
                components[graph[v][u]]=no_of_components;
    
            }
    

    然后按预期工作。

    Online demo

    【讨论】:

    • @hetajr 为避免任何疑问,我更新了在线演示以显示图表并显示使用算法的更正版本识别的分组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多