【问题标题】:Finding connected components in graph (adjA) using DFS使用 DFS 在图形 (adjA) 中查找连通分量
【发布时间】:2017-02-05 18:07:46
【问题描述】:

我今天一直在互联网上搜索,试图弄清楚如何在邻接列表vector<list<edge>> adjA 上运行 DFS,但我就是不知道如何正确地做到这一点。我能在网上找到的最好的例子是:Find connected components in a graph 但是使用他的第一种方法似乎不起作用,我对联合/集合没有足够的信心尝试他的其他方法。这是我目前所拥有的:(忽略test_vectorcc,我专注于让cc_count 工作)

edge 是一个结构体,包含:

struct edge{
    int to; //copy of to_original (dont worry about this it's for a different functionality)
    int w; //weight of edge
    int from_original; //from vertex
    int to_original;  //to vertex
}

在 int main 中的某处:

cout << "conn: " << connected(adjA, test_vector) << endl;

int connected(vector<list<edge>> &adjA, vector<short int> &cc){
        int v_size = adjA.size();
        vector<bool> discovered(false,v_size);
        int cc_count = 0;
        for(unsigned int u = 0; u < adjA.size(); u++){
            if(!discovered[u]){
                cout << u << endl;
                discovered[u] = true;
                cc_count+=1;
                dfs(adjA,discovered,cc,cc_count,u);
            }
        }
        return cc_count;
    }

    void dfs(vector<list<edge>>&adjA, vector<bool> &discovered, vector<short int> &cc, int &cc_count,int u){
    for(unsigned int v = 0; v < adjA[u].size();v++){
        if(!discovered[v]){
            cout << v << endl;
            discovered[v] = true;
            dfs(adjA, discovered,cc,cc_count,v);
        }
    }

    }

cout &lt;&lt; v &lt;&lt; endl;cout &lt;&lt; u &lt;&lt; endl 行开始,它将显示它能够访问每个节点一次。但是,我认为我错误地增加了cc_count。在这个邻接列表中:

0->[1]->[3]->[5]
1->[0]->[2]->[3]->[4]
2->[1]->[4]
3->[0]->[1]->[4]->[5]
4->[1]->[2]->[3]->[5]->[6]
5->[0]->[3]->[4]->[6]
6->[4]->[5]

程序将输出:

0
1
2
3
4
5
6
conn: 7

当 conn 应该为 1 时,因为整个图是一个单独的组件。我觉得我可能会以错误的方式解决这个问题。有什么我应该做的改变吗?使用 DFS 或 BFS 是否有更好的方法来做到这一点?

我为糟糕的格式道歉,我花了将近一个小时试图让堆栈溢出错误消失。

邻接表表示的图

【问题讨论】:

    标签: c++ list vector depth-first-search adjacency-list


    【解决方案1】:

    您的dfs 方法根本没有查看边缘。我不知道edge 是什么问题,但我们假设它是pair-like(两个端点)。

    然后

    for(unsigned int v = 0; v < adjA[u].size();v++) {
        // do something with v
    }
    

    应该是

    for (auto const & e: adjA[u]) {
        // do something with the endpoint of e other than u
    }
    

    【讨论】:

    • 好的,所以edge 提供了两个端点。你只需要使用一个不是u 的,命名为v 并使用你以前的代码。
    猜你喜欢
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多