Java 深度优先搜索难题
不知道如何在我的代码中实现深度优先搜索算法。以下是解决以下问题的广度优先搜索算法示例:Java 深度优先搜索难题,java,depth-first-search,Java,Depth First Search,不知道如何在我的代码中实现深度优先搜索算法。以下是解决以下问题的广度优先搜索算法示例: public direction[]解决(nPuzzle难题){ //此方法使用条纹作为队列。 //因此,按成本的顺序搜索节点,成本最低 //下一步搜索未探测节点。 //----------------------------------------- //将开始状态置于边缘以进行探索。 addToFrontier(puzzle.StartState); ArrayList newStates=新的Array
public direction[]解决(nPuzzle难题){
//此方法使用条纹作为队列。
//因此,按成本的顺序搜索节点,成本最低
//下一步搜索未探测节点。
//-----------------------------------------
//将开始状态置于边缘以进行探索。
addToFrontier(puzzle.StartState);
ArrayList newStates=新的ArrayList();
while(Frontier.size()>0)
{
//把下一件衣服从边缘上拿下来
PuzzleState thisState=popFrontier();
//这是目标项目吗?
if(thisState.equals(puzzle.GoalState))
{
//我们找到了解决方案!退回!
返回thisState.GetPathToState();
}
其他的
{
//这不是目标,只是探索节点
newStates=thisState.explore();
对于(int i=0;i
还有更多的代码
非常感谢您的帮助。实现中的主要区别是:在DFS中,要探测的节点存储在stck中,而在BFS中,它们存储在队列中
B对于您试图解决的难题,我认为BFS更合适,因为您正在搜索最短路径。
要获得更多帮助,请发布帖子,这样我们就不必做很多猜测 你需要什么帮助?代码中有什么不起作用?我需要实现一个深度优先搜索算法来解决一个8字难题。我不知道如何继续扩展子节点,直到它到达终点或找到解决方案。如果广度优先搜索通过向上、向下、向左、向右状态添加到newStates来“探索”当前状态,那么它们将被添加到要探索的前沿。我将如何继续探索儿童状态。例如,探索向上状态,然后向上,向上状态,然后向上,向上,向上,向上,向左。而不是探索向上的状态,然后是向左的状态,然后是向右的状态
public direction[] Solve(nPuzzle puzzle) {
//This method uses the fringe as a queue.
//Therefore, nodes are searched in order of cost, with the lowest cost
// unexplored node searched next.
//-----------------------------------------
//put the start state in the Fringe to get explored.
addToFrontier(puzzle.StartState);
ArrayList<PuzzleState> newStates = new ArrayList<PuzzleState>();
while(Frontier.size() > 0)
{
//get the next item off the fringe
PuzzleState thisState = popFrontier();
//is it the goal item?
if(thisState.equals(puzzle.GoalState))
{
//We have found a solution! return it!
return thisState.GetPathToState();
}
else
{
//This isn't the goal, just explore the node
newStates = thisState.explore();
for(int i = 0; i < newStates.size(); i++)
{
//add this state to the fringe, addToFringe() will take care of duplicates
addToFrontier(newStates.get(i));
}
}
}
//No solution found and we've run out of nodes to search
//return null.
return null;
}