我正在解决这个dfs/bfs问题。
我编写了 DFS 的迭代版本和递归版本。
节点访问的顺序不同,我不明白为什么。
迭代 DFS:
static void DFS (Integer root, Graph graph){
// System.out.println("DFS");
HashSet <Integer> explored = new HashSet<Integer>();
explored.add(root);
Stack<Integer> stack = new Stack<Integer>();
stack.add(root);
int v; int w;
while (!stack.isEmpty()){
v=stack.pop();
explored.add(v);
System.out.print(v + " ");
// for (int i=graph.adjacencies.get(v).size()-1; i>=0; i--) {
for (int i=0; i < graph.adjacencies.get(v).size(); i++) {
w = graph.adjacencies.get(v).get(i);
if (!explored.contains(w)){
stack.add(w);
explored.add(w);
}
}
}System.out.println();
}
递归 DFS:
static void DFS_2 (Integer root, Graph graph){
// System.out.println("DFS_2");
int v; int w;
v = root;
graph.explored.add(v);
System.out.print(v + " ");
for (int i=0; i < graph.adjacencies.get(v).size(); i++) {
w = graph.adjacencies.get(v).get(i);
if (!graph.explored.contains(w)){
graph.explored.add(w);
DFS_2(w, graph);
}
}
}
在教程问题上,我在迭代 DFS 版本上的输出是
1 4 3 2 6
虽然应该是(根据问题示例输出和递归版本):
1 3 2 6 4
这里发生了什么事?为什么消除递归会改变访问节点的顺序?
-> Netbeans 项目的完整代码。