【发布时间】:2016-10-31 18:09:26
【问题描述】:
我正在尝试构建一个程序,在 15 人游戏中比较算法 BFS、DFS、A*(具有两个启发式)的笔画数。
我的计数器对 BFS 和 DFS 以及 A* 的两个计数器数组的计数相同。然而,我实际上使用了来自主(项目类)的四个不同数组,并且我为这些笔画分配了四个不同的变量。
在我看来,不正确的代码部分是一个 while 循环,它尽可能地探索一个顶点的儿子(对于 BFS)或发现每个后续节点(对于 BFS)。最重要的区别是代码的最后一行是 frontier.push(child);,对于 DFS,或 frontier.add(child);用于 BFS。
每进入循环,笔画数就递增一次
number_of_strokes_DFS+=1;
或
number_of_strokes_BFS+=1;
当我们找到最终状态时,我们将结果添加到笔画数数组中:
array_number_of_strokes_dfs.add(number_of_strokes_DFS);
或
array_number_of_strokes_bfs.add(number_of_strokes_BFS);
最后是有罪的代码(实际上只有 DFS,因为 BFS 真的很像,除了最后一行)。
while(!frontier.isEmpty()){
number_of_strokes_DFS+=1;
if(System.currentTimeMillis()-startTime>10000)break;
// We remove the current state from the frontier
current_state = frontier.pop();
// We get all possible actions from the current state
actions = current_state.getActions();
// We add the current state to already explored nodes
explored_nodes.add(current_state);
//System.out.println(current_state);
path.add(current_state);
// we found the goal
if(goal_test(current_state)){
/*for(State visited :path){
System.out.println(visited);
}*/
array_number_of_strokes_dfs.add(number_of_strokes_DFS);
System.out.println("nombres de coups DFS"+number_of_strokes_DFS);
number_of_strokes_DFS=0;
return current_state;
}
// We create every child
for (Action action : actions){
//System.out.println("action : " + action);
// we get a child from the execution of the current_state
State child = current_state.execute(action);
//System.out.println("we executed the action");
if(!explored_nodes.contains(child)&&!frontier.contains(child)){
// This child not being already explored nor int the frontier we add it to the last one
frontier.push(child);
}
}
}
array_number_of_strokes_dfs.add(-1);
return finalState;
}
当我让 array_number_of_strokes_dfs.add(number_of_strokes_DFS); 时,这是实际问题,例如,我总是得到与数组中的 BFS 相同的结果。它可能发生一次,但不是每次都发生! 而如果我添加一个零
array_number_of_strokes_dfs.add(0);
我确实看到了区别......
你有什么想法吗?
结果如下:
strokes BFS : [3, 27, 27, 26, 26, 2631, 7]
strokes DFS[3, 27, 27, 26, 26, 2631, 7]
【问题讨论】:
-
frontier的类型是什么? -
@Ishamael 嗨!它是一个状态堆栈
Stack<State> frontier = new Stack<State>();它写在我在算法函数中显示的循环的上方。
标签: java arrays algorithm breadth-first-search depth-first-search