【发布时间】: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