【问题标题】:how to check presence of cycle in undirected graph?如何检查无向图中是否存在循环?
【发布时间】:2017-02-28 04:10:02
【问题描述】:
#include <bits/stdc++.h>
        using namespace std;
    int n,m;
    vector<int> adj[51];
    int visited[51];
    bool flag;
    void dfs(int i,int parent){
        vector<int>::iterator it;
        for(it = adj[i].begin();it!=adj[i].end();it++){
            if(!visited[*it]){
                visited[*it]=1;
                dfs(*it,i); // passing parent element
            }
            if(visited[*it] && (*it !=parent )){
                flag=true; return;
            }
        }
    }
    int main(){
        int a,b;
        cin>>n>>m;
        for(int i=0;i<m;i++){  // graph ready.
            cin>>a>>b;
            if(a==b){
                cout<<"YES"; return 0;
            }
            adj[a].push_back(b);
            adj[b].push_back(a);
        }
        for(int i=1;i<=n;i++){
            std::vector<int>::iterator it;
            for(it=adj[i].begin();it!=adj[i].end();it++){
                if(!visited[*it]){
                    visited[*it]=1;
                    dfs(*it,-1);
                }
            }
        }
        if(flag){
            cout<<"YES"<<endl;
        }else{
            cout<<"NO"<<endl;
        }
    }

谁能检查我的代码并告诉我这里缺少哪个测试用例。在hackerearth 上只有60 /100。我在这里使用父变量来跟踪被认为是循环的单个边缘。

【问题讨论】:

    标签: data-structures graph graph-algorithm depth-first-search undirected-graph


    【解决方案1】:

    您得到了错误的输出,因为在adjacency list 每条边都列出了两次。

    假设我们有 3 vertices2 edges 的图表:

    1------2------3
    

    显然,不存在循环。但是您的代码也为此输入返回 YES。原因是一旦特定顶点i由于其父级j而被访问,下次调用idfs时,顶点j将被访问,因此,输出是的,这是错误的。

    修复

    每当我们访问一个已经访问过的顶点i时,我们不会立即声明我们找到了一个循环,我们必须确保顶点i不是我们调用的dfs的顶点的父节点,只有这样你才能得到正确的答案。

    一旦你明白了哪里出了问题,代码就更容易编写了。

    【讨论】:

    • @SahilKumar 一点也不。
    • @SahilKumar 对于有向图,您需要具有时间戳以及 dfs 算法。所以这是完全不同的方法。
    猜你喜欢
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多