【发布时间】:2014-12-17 20:17:20
【问题描述】:
我目前正在尝试在从源到接收器的图中找到一条路径。我正在尝试使用 dfs 实现一种方法来实现这一点。但是,我似乎无法弄清楚如何制作停止递归的方法。例如,我有这个图(矩阵形式)
0 1 1 0
0 0 0 1
0 0 0 1
0 0 0 0
所以我有一条从节点 0(源)到节点 1 和 2 的边,然后有一条从 1 和 2 到 3(接收器)的边。我想要的路径是 0>1>3,而不是我得到 0>1>3>2>3。一旦找到到接收器的路径,如何使递归停止?
这里是方法的代码:
public void dfsPath(int i) {
boolean[] visited = new boolean[this.edgeCapacities.length];
visited[i] = true;
this.path.add(i); //Integer ArrayList containing the nodes in the path
//loop through all of the nodes in the matrix to find adjacency
for (int j = 0; j < this.edgeCapacities.length; j++) {
//check if edge exists and node has not been visited
if (this.edgeCapacities[i][j] != 0 && !visited[j]) {
//here is the problem, i want the recursion to stop once the sink is found
//it does not work however.
if(j == this.sink) {
visited[j] = true;
this.path.add(j);
return;
} else {
//recursion
dfsPath(j);
}
}
}
任何帮助将不胜感激。提前致谢。
【问题讨论】:
-
您的 dfs 算法似乎已损坏。见this link。
-
@Everv0id 我看不到问题所在。解释一下?
标签: java recursion matrix path depth-first-search