【问题标题】:How to find the path between 2 nodes in a tree?如何找到树中两个节点之间的路径?
【发布时间】:2020-04-12 21:49:40
【问题描述】:

我正在尝试使用 java 查找树的 2 个节点之间的路径,但我得到了错误的答案

'''

public static void dfs(int source ,int destination ,ArrayList<Integer> path ,ArrayList<Integer> graph[] ,boolean vis[]){
    path.add(x);
    if(source == destination)
    return ;
    vis[source] = true;
    flag = 0;
    if(graph[source].size()!=0){
        for (int j : graph[source]){
            if(vis[j] == false){
                dfs(j,destination,path,graph,vis)
                flag = 1;
            }
        }
    }
    if(flag == 0){
        path.remove(path.size()-1);
    }
}

'''

对于一个由 11 个节点组成的树,其边被给定
1 2
2 3
2 4
2 8
4 5
4 6
4 7
8 9
8 10
8 11
节点 1 和 8 之间的路径应该是:1->2->8 但使用此代码,结果是 1->2->4->8
类似地,节点 3 和 6 之间的路径应该是:3->2->4->6,但是这段代码会产生输出:3->2->4->6->8。 为什么会这样?

【问题讨论】:

    标签: java graph tree depth-first-search


    【解决方案1】:

    您确实有一些变量未在dfs 方法中声明。特别是在递归调用中,需要注意什么应该声明为局部变量,什么应该通过参数传递,什么可以声明为全局静态变量。

    您对dfs 的回溯实现不正确。您在path 中累积您遍历的所有节点,而不是到目标的路径。

    您需要重新设计代码。例如,您的函数可能会返回一个布尔值,而不是返回 void,搜索是否成功。然后您可能决定不再更改path。或者,您的函数可能会将path 返回到目标。

    dfs 的更好实现可能是:

    public static boolean dfs(int source, int destination, 
                              List<Integer> path, 
                              List<Integer> graph[], 
                              boolean vis[]) {
        path.add(source);
        if (source == destination) {
            return true;
        }
        vis[source] = true;
        if (!graph[source].isEmpty()) {
            for (int j : graph[source]) {
                if (!vis[j]) {
                    if (dfs(j, destination, path, graph, vis)) {
                        return true;
                    }
                }
            }
        }
        path.remove(path.size() - 1);
        return false;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多