如何解决使用自底向上的DFS查找两个节点之间的所有路径
所以我试图解决以下经典练习
给出一个具有整数节点值以及给定源和目标整数的图,找到所有从源到目标的路径。
我想出了一种算法,以自上而下的方式解决问题
import java.util.*;
class Scratch {
static class Node {
public int value;
public Set<Node> neighbours;
public Node(int value) {
this.value = value;
this.neighbours = new HashSet<>();
}
}
public static void dfs(int target,Node current,Set<Node> visited,Stack<Integer> currentPath) {
if (current == null || visited.contains(current)) return;
if (current.value == target) {
// found target. print solution
StringBuilder builder = new StringBuilder();
for (Integer val : currentPath) {
builder.append(" ");
builder.append(val);
}
builder.append(" ");
builder.append(current.value);
System.out.println(builder.toString());
return;
}
// add current node to path
currentPath.push(current.value);
visited.add(current);
// visit neighbours
for (Node neighbour : current.neighbours) {
dfs(target,neighbour,visited,currentPath);
}
// remove current node from path
currentPath.pop();
visited.remove(current);
}
public static void dfs(int target,Node root) {
dfs(target,root,new HashSet<>(),new Stack<>());
}
public static void main(String[] args) {
/**
* Find paths between 1 and 3 for the following graph:
* 2
* / |
* 1 --3
* \
* 4
*/
Node one = new Node(1);
Node two = new Node(2);
Node three = new Node(3);
Node four = new Node(4);
Node root = one;
root.neighbours.add(two);
root.neighbours.add(three);
root.neighbours.add(four);
two.neighbours.add(three);
dfs(3,root);
// prints:
// -> 1 2 3
// -> 1 3
}
}
因此,其背后的想法是像平常使用dfs一样遍历所有图形,但是在跳转到邻居之前,我将在进行递归调用之前将当前节点添加到路径,然后将其从路径中删除。这样,我可以跟踪从源头开始的所有当前路径,一旦到达目标,我就将其打印出来。
我在考虑是否可以使用自底向上算法来完成;我无法考虑如何遵循相同的想法,因为在这种方法中,我们会在不久的将来“排队访问”邻居,因此我们不能像在自上而下的方法中所做的那样,仅从路径中删除当前节点。
有什么想法或提示吗?预先感谢
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。