简体   繁体   English

我的DFS代码有什么问题?

[英]What's Wrong In My DFS Code?

I have tried to Implement Recursive DFS as I found at TH Cormen's Book . 我试图实现递归DFS,正如我在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 . 我已经将代码编写为TH Cormen's Algorithm Book。

Here is one problem 这是一个问题

if(color[v]=-1)

That is setting color[v] to -1 . 那就是将color[v]设置为-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) if(color [v] =-1)将是if(color [v] ==-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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