简体   繁体   中英

What's Wrong In My DFS Code?

I have tried to Implement Recursive DFS as I found at TH Cormen's Book . I implemented the Algorithm . But the program Crashed . Here is my Code:

#include<bits/stdc++.h>

using namespace std;

vector<int>graph[100];
int tim;
int start[100], finish[100], path[100], color[100];

void DFS_Visit(int u)
{
    color[u] = 0;
    tim = tim + 1;
    start[u] = tim;
    for(int i=0; i<graph[u].size(); i++)
    {
        int v = graph[u][i];
        if(color[v]=-1)
        {
            path[v] = u;
            DFS_Visit(v);
        }
    }
    color[u] = 1;
    tim = tim + 1;
    finish[u] = tim;
}

int main()
{
    int nodes, edges, u, v;
    cin>>nodes>>edges;
    for(int i=0; i<edges; i++)
    {
        cin>>u>>v;
        graph[u].push_back(v);
        graph[v].push_back(u);
    }
    for(int i=1; i<=nodes; i++)
    {
        color[i] = -1;
        path[i] = -1;
        //cout<<'1'<<endl;
    }
    tim = 0;
    for(int i=1; i<=nodes; i++)
    {
        //cout<<'1'<<endl;
        if(color[i]==-1)
        {
            DFS_Visit(i);
        }
    }
    for(int i=1; i<=nodes; i++)
    {
        printf("Node %d: Starting_Time: %d || Finishing Time: %d\n", i, start[i], finish[i]);
    }
    return 0;
}

Can anyone please learn me What's wrong with my Code? What to do to resolve this Problem . I have written the Code as TH Cormen's Algorithm Book .

Here is one problem

if(color[v]=-1)

That is setting color[v] to -1 .

I am surprised your compiler didn't generate a warning for this.

I have Got My error . That is

if(color[v]=-1) will be if(color[v]==-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM