我已經編寫了深度優先搜索算法,但是它從樹的右側向左搜索。我可以從代碼中看到它爲什麼這樣做,但我無法想出一個解決方案來更改它,以便從左到右進行搜索。DFS算法正在從右向左搜索
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
既然你指出了,我不知道它的目的是什麼!基本上我只是想放棄那個節點。我現在將編輯我的代碼 – KOB
@ user2357112固定。 – KOB