-1
#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;
        }
    }

can anyone check my code and tell me which test case i'm missing here. got only 60 /100 on hackerearth. i'm using parent variable here to keep track of a single edge considered to be a loop.

Sahil Kumar
  • 39
  • 1
  • 3
  • 9

1 Answers1

0

You are getting the wrong output because in adjacency list every edge is listed twice.

So say we have the graph with 3 vertices and 2 edges as:

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

Clearly, no cycle is there. But you code returns YES for this input as well. Reason is once a particular vertex i gets visited due to its parent j, Next time when dfs for i is called, vertex j, will come out to be visited and therefore, output YES , which is wrong.

FIX

Whenever we visit a vertex i, which is already visited, we do not immediately declare that we have found a cycle, We must make sure that vertex i , is not the parent of vertex whose dfs we called, only then you will get the right answer.

The code is easier to write , once you have understood what is going wrong.

Sumeet
  • 8,086
  • 3
  • 25
  • 45