DFS - 两个节点之间的路由

时间:2018-03-21 01:33:18

标签: c# graph-theory depth-first-search

我构建了一个Graph类,它包含各种节点和它们之间的有向边。我正在尝试运行递归DFS算法,我正在检查两个节点之间是否存在路径。

public static bool RouteBetweenNodes_DFS(Node a, Node b) {
    if (a == null || b == null)
        return false;

    // If we haven't returned 'true' yet, we mark the node as visited and visit its children
    a.visited = true;

    Console.WriteLine("A: " + a.data + ", B: " + b.data);
    // We use this as our truth condition when we recurse.
    if (a == b) {
        Console.WriteLine("Match: returning true");
        return true;
    }


    foreach (var child in a.children) {
        if (!child.visited) {
            //Console.WriteLine(child.data);
            Console.WriteLine("Before recursion: " + child.data);
            RouteBetweenNodes_DFS(child, b);
            Console.WriteLine("After recursion: " + child.data);
        }
    }

    return false;
}

但是,这不起作用。该图如下所示:

enter image description here

控制台打印输出:

A: 2, B: 6
Before recursion: 8
A: 8, B: 6
Before recursion: 4
A: 4, B: 6
After recursion: 4
After recursion: 8
Before recursion: 5
A: 5, B: 6
Before recursion: 6
A: 6, B: 6
Match: returning true
After recursion: 6
After recursion: 5
Before recursion: 3
A: 3, B: 6
Before recursion: 6
A: 6, B: 6
Match: returning true
After recursion: 6
After recursion: 3

由于某种原因,似乎return语句的值没有传播到顶层。我也试过return RouteBetweenNodes(...),但这甚至没有适当搜索。

非常感谢任何帮助。

0 个答案:

没有答案