Depth first search(DFS)

closed account (1vf9z8AR)
Problem-
https://www.spoj.com/problems/PT07Y/

Issue-
getting wrong answer on spoj but test cases are getting the right output.

My technique-
check if each node visited
check if cycle is present.

if cycle present or each node not visited then it is not a tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  // adj is for adjacent nodes
//visited is to check if visited or not
// parent is parent node
//prev is previous node
//current is current node
#include<iostream>
#include<vector>
using namespace std;
bool cycle(vector<int>adj[],bool visited[],int parent,int prev,int current)
{
    if(visited[current]==true && current!=parent)
    {
        return true;
    }
        for(auto x:adj[current])
        {
            visited[current]=true;
            if(x!=prev)
                cycle(adj,visited,prev,current,x);
        }
}
int main()
{
    int n,m;
    cin>>n>>m;
    if(n!=m+1)
    {
        cout<<"NO";
        return 0;
    }
    bool hascycle=false;
    vector<int>adj[n+1];
    int t1,t2;
    vector<int>node;
    for(int i=0;i<m;i++)
    {
        cin>>t1>>t2;
        adj[t1].push_back(t2);
        adj[t2].push_back(t1);
        node.push_back(t1);
        node.push_back(t2);
    }
    bool visited[n+1];
    for(auto x:node)
    {
        visited[x]=false;
    }
    hascycle=cycle(adj,visited,1,1,1);
   for(auto x:node)
    {
        if(visited[x]==false)
        {
            cout<<"NO";
            return 0;
        }
    }
    if(hascycle==true)
        cout<<"NO";
    else
        cout<<"YES";
    return 0;
}

hascycle stores the condition if cycle exists or not.
node stores all nodes.
Last edited on
In function ‘bool cycle(std::vector<int>*, bool*, int, int, int)’:
warning: control reaches end of non-void function [-Wreturn-type]



and a testcase
2 1
1 1



also, `visited[1]' may remain uninitialised but you'll try to access it on cycle()
closed account (1vf9z8AR)
@ne555
thanks, it got accepted.

I can't believe it, codeblocks will give me "yes" and the online compiler will give me "no" :|

after adding return false; to end of cycle() problem was fixed.
Different compilers can give different warnings. Especially if they're using different options for their warning levels.

As a general rule, it's best to tell your compiler to show you as many warnings as possible. Because why wouldn't you want it to point out things in your code that need fixing?
closed account (1vf9z8AR)
ok.
Topic archived. No new replies allowed.