【发布时间】:2017-02-05 16:07:33
【问题描述】:
我写了一个深度优先搜索算法,但它是从树的右侧向左搜索。我可以从我的代码中看到它为什么这样做,但我无法想出一个解决方案来改变它,以便它从左到右搜索。
public class DFS {
public LinkedList<Node> search(Node root, Node target) {
LinkedList<Node> open = new LinkedList<>();
LinkedList<Node> closed = new LinkedList<>();
open.addLast(root);
while (!open.isEmpty()) {
Node current = open.removeFirst();
if (current.equals(target)) {
closed.addLast(current);
return closed;
}
else {
ArrayList<Node> children = current.getChildren();
closed.addLast(current);
for (Node child : children) {
if (!open.contains(child) && !closed.contains(child)) {
open.addFirst(child);
}
}
}
}
return null;
}
}
closed 是按访问顺序排列的节点列表。
Node.getChildren() 按添加顺序返回节点子节点的 ArrayList。
编辑
这里是节点类:
public class Node {
private ArrayList<Node> children;
private String name;
public Node(String name){
children = new ArrayList<Node>();
this.name = name;
}
public ArrayList<Node> getChildren(){
return new ArrayList<Node>(children);
}
public Node addChild(Node child){
children.add(child);
return child;
}
public void removeChild(Node child){
children.remove(child);
}
public String getName() {
return name;
}
public boolean equals(Node other){
return (this.getName().compareTo(other.getName())==0);
}
}
【问题讨论】:
-
你为什么要做
children.remove(child),尤其是在children的循环期间? -
既然你指出来了,我不知道它有什么用!基本上我只是想丢弃那个节点。我现在将编辑我的代码
-
@user2357112 已修复。
-
我有点困惑:标题提到DepthFS,类名是BFS。哪个是错字?只是为了确定,你想要深度优先还是广度优先?在粗略检查您的代码时,我没有看到来自
closed的任何pop,这对于 DFS 来说是不寻常的 - 当然,您会有无法得到答案的分支,需要被丢弃。 -
@AdrianColomitchi 我的错,当我在几分钟后编辑我的问题时,我想我复制并粘贴了我的 BFS 算法。我现在已经修好了。
closed返回一个正确的 DFS 搜索模式,但它会尽可能沿着树的右侧而不是左侧移动
标签: java search tree depth-first-search