0
我期望DFS方法打印路徑爲1-> 2-> 4-> 5,但它顯示1-> 2-> 3-> 4-> 5請問您可以提示方法可以使用最少的代碼量來修正?DFS方法不能正常工作
/**
* Created by mona on 5/28/16.
*/
import java.util.Stack;
public class DepthFirstSearch {
public static void DFS(GraphNode root, int num) {
if (root.val == num) {
System.out.println("root has the value "+num);
}
System.out.println(" current value is "+root.val);
Stack<GraphNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
for (GraphNode g : stack.pop().neighbors) {
if (!g.visited) {
System.out.println(" current value is "+g.val);
if (g.val == num) {
System.out.println("Found");
}
g.visited = true;
stack.push(g);
}
}
}
}
public static void main(String[] args) {
GraphNode n1 = new GraphNode(1);
GraphNode n2 = new GraphNode(2);
GraphNode n3 = new GraphNode(3);
GraphNode n4 = new GraphNode(4);
GraphNode n5 = new GraphNode(5);
n1.neighbors = new GraphNode[] {n2};
n2.neighbors = new GraphNode[] {n4,n3};
n3.neighbors = new GraphNode[] {n4};
n4.neighbors = new GraphNode[] {n5};
n5.neighbors = new GraphNode[] {};
DFS(n1, 5);
}
}
下面是GraphNode類的代碼:
/**
* Created by mona on 5/27/16.
*/
public class GraphNode {
int val;
GraphNode next;
GraphNode[] neighbors;
boolean visited;
GraphNode(int val) {
this.val = val;
this.visited = false;
}
GraphNode(int val, GraphNode[] neighbors) {
this.val = val;
this.neighbors = neighbors;
this.visited = false;
}
public String toString() {
return "value is: "+this.val;
}
}
所以這個問題是使用'爲(GraphNode G:堆棧。 pop()。neighbors){'? –
運行你的代碼,我仍然得到相同的結果http://pastebin.com/hj5P8CpL –
@MonaJalal:對不起,這是你從堆棧中彈出它們的順序。我沒有注意到你在將它們添加到堆棧時將它們打印出來......但是如果你想要一個路徑,只需添加所有找到的節點就不夠了......爲此添加了一個修復程序。 – fabian