我一直在寻找一种算法来打印有向图中两个节点之间的所有可能路径。
我看到了这个:
procedure FindAllPaths(u, dest)
{
push u to stack;
if(u == dest)
{
print stack;
}
else
{
foreach v that is adjacent with u and not in stack now
{
FindAllPaths(v, dest);
}
}
pop from stack;
}
但是当我运行它时,它会打印一条正确的路径并进入无限循环并打印出这些路径! 问题是什么?
特别感谢,
答案 0 :(得分:1)
这是您的算法的JavaScript实现,带有示例图。它在这里工作。如果您发现实施方式存在差异,请发布更多信息:
var edges = [
{from:0, to:0},
{from:0, to:1},
{from:0, to:2},
{from:1, to:3},
{from:2, to:3},
{from:2, to:0}
];
var stack = [];
function FindAllPaths(u, dest) {
stack.push(u);
if(u === dest)
{
console.log(stack.join('->'));
}
else
{
for(i in edges) {
var edge = edges[i];
if (edge.from == u && stack.indexOf(edge.to) < 0) {
FindAllPaths(edge.to, dest);
}
}
}
stack.pop();
}
FindAllPaths(0, 3);