[英]back and forward edges in directed graph
I am new to graph theory. 我是图论的新手。 I am writing a code to find all forward and back edges in directed graph.
我正在编写代码以查找有向图中的所有前向和后向边缘。 I searched and implemented the code as below.
我搜索并实现了以下代码。 My code is going into infinite loop.
我的代码进入了无限循环。 Could you please have a look.
你能看看吗。 We will very greateful to you.
我们将非常感谢您。
void dfsVisit(u)
{
u->color="gray";
u->time=count;
count++;
for(every child node v of u)
{
if(v->color == "black")
{
if(u->time < v->time)
cout<<"Edge "<<u<<"->"<<v<<" is forward edge"<<endl;
else
cout<<"Edge "<<u<<"->"<<v<<" is cross edge"<<endl;
}
if(v->color == "gray")
cout<<"Edge "<<u<<"->"<<v<<" is back edge"<<endl;
if(v->color == "white")
cout<<"Edge "<<u<<"->"<<v<<" is tree edge"<<endl;
dfsVisit(v);
}
u->color="black";
u->time=count;
count++;
}
I see two possible problems with your code: 我发现您的代码有两个可能的问题:
you call dfsVisit
for every child, regardless of its color. 您
dfsVisit
为每个孩子调用dfsVisit
,无论其颜色如何。 You indented it into a deeper level, but you didn't add any parenthesis around the white if - based on this pseudocode, only the cout
is affected by the if statement. 您将其缩进了更深的层次,但是您没有在白色if周围加上任何括号-基于此伪代码,if语句仅影响
cout
。 But since this is just a pseudocode, you should post the original C++ code you wrote to be clear. 但是,由于这只是一个伪代码,因此应该清楚地写出编写的原始C ++代码。
you have three colors in your conditions (grey, black, and white), but you never set white anywhere. 您可以在自己的条件下使用三种颜色(灰色,黑色和白色),但是您永远不会在任何地方设置白色。 Your edges are initialized to white before you call
dfsVisit
? 在调用
dfsVisit
之前,边缘已初始化为白色。 (you should consider using an enum or enum class for the colors, it's cleanear and you'll less likely to cause bugs with typos) (您应该考虑将enum或enum类用于颜色,它是无污染的,并且不太可能导致拼写错误)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.