[英]How to find the path between 2 nodes in a tree?
我正在嘗試使用 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,但此代碼產生 output:3->2->4->6->8。 為什么會這樣?
您確實有一些未在dfs
方法中聲明的變量。 特別是在遞歸調用中,需要注意什么應該聲明為局部變量,什么應該通過參數傳遞,什么可以聲明為全局變量static。
您對dfs
的回溯實現不正確。 您累積path
中遍歷的所有節點,而不是目標路徑。
你需要重新設計你的代碼。 例如,您的 function 可能會返回 boolean 而不是返回 void,而不管搜索是否成功。 然后你可能決定不再改變path
。 或者,您的 function 可能會將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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.