Java BFS中的目标检查
根据我所学的内容,我尝试用JAVA实现BFS算法,但我有点困惑,我不确定我是在检查节点是目标还是在适当的位置将节点添加到列表中。代码如下:Java BFS中的目标检查,java,breadth-first-search,Java,Breadth First Search,根据我所学的内容,我尝试用JAVA实现BFS算法,但我有点困惑,我不确定我是在检查节点是目标还是在适当的位置将节点添加到列表中。代码如下: frontier.add(nodes.getFirst());//node.isGoal is only true if the node is desired node if(frontier.getFirst().isGoal)//Checking if the root node is goal { explored.a
frontier.add(nodes.getFirst());//node.isGoal is only true if the node is desired node
if(frontier.getFirst().isGoal)//Checking if the root node is goal
{
explored.add(frontier.getFirst());
prev.put(frontier.getFirst(), null);
goalNode = explored.getFirst();
frontier.poll();
}
while (!frontier.isEmpty())
{
currentNode = frontier.poll();
explored.add(currentNode);
for (Node node : currentNode.children) {//adding node children to fronier and checking if they are goal
if (!frontier.contains(node) || !explored.contains(node)) {
frontier.add(node);
prev.put(node, currentNode);//mapping nodes to parent node to return sequence of nodes
if (node.isGoal) {
goalNode = node;
break;
}
}
}
}
提前感谢。根据我对您代码的理解,您似乎做错了:您检查初始集合中的第一个节点(例如树级),如果它不是目标节点,则添加尚未在
frontier
中且尚未访问的子节点。没关系,但可能没有必要。错误的是,您在检查家长的兄弟姐妹之前先检查孩子,因此您的搜索并不完全是广度优先
那么你可以/应该做什么
假设您的数据表示一棵树(宽度优先表示这棵树),并且您从某个级别(例如根节点)开始。由于数据是广度优先方法中的一棵树,任何未访问过的子级都不可能已经访问过,而且可能也不在您的frontier
列表中,因此无需检查(如果您有更一般的图形,则可能不是这样)
因此,算法可以如下所示:
LinkedList<Node> frontier = new LinkedList<>();
//assuming you always have a root node just add it
frontier.add( root );
Node goal = null;
//loop until the list is empty, if we found a goal node we'll break the loop from the inside
while( !frontier.isEmpty() ) {
//get the node at the start of the list and remove it
//in the first iteration this will be the root node
Node node = frontier.pop();
//found a goal so we're done
if( node.isGoal ) {
goal = node ;
break; //this breaks the while loop
}
//didn't find a goal yet so add the children at the end
if( node.children != null ) {
frontier.addAll( node.children );
}
}
LinkedList frontier=新建LinkedList();
//假设您总是有一个根节点,只需添加它即可
frontier.add(root);
节点目标=null;
//循环直到列表为空,如果我们找到一个目标节点,我们将从内部打破循环
while(!borine.isEmpty()){
//获取列表开头的节点并将其删除
//在第一次迭代中,这将是根节点
Node=frontier.pop();
//找到一个目标,我们就完成了
if(node.isGoal){
目标=节点;
break;//这将中断while循环
}
//还没有找到目标,所以在最后加上孩子们
if(node.children!=null){
frontier.addAll(node.children);
}
}
这样做意味着您在末尾添加下一级(子级)的节点,并从前面将节点弹出到树的更高位置,直到找到要搜索的内容。这意味着列表中应该始终只有树的一个或两个级别,即当前级别以及任何已处理的当前级别节点的直接子级
正如您所看到的,由于我们在树上操作,因此不需要保留explored
集
此外,您可能需要考虑是否确实需要在迭代期间构建该
prev
映射,因为您可能需要再次删除元素,并且映射并不真正适合获取从目标节点到根节点的路径。您可能希望在每个节点中保留一个指向父节点的链接,因此,一旦找到目标节点,您只需向上迭代,直到到达根节点。您可能希望提供更多有关您尝试执行的操作的信息(例如,isGoal
是否意味着它是一个可能的目标节点,或者它已经是您正在搜索的目标节点?在中,如果(node.isGoal)
您似乎保留了一个目标节点,但继续在边界上迭代
-您真的只想保留最后一个goalNode
,它可能在树中更深一些?)以及你的代码中关于你认为你在做什么的一些评论。你的代码有没有问题,比如没有得到预期的结果?如果有,请发布输入、预期的输出和你得到的结果。我希望编辑是足够的。我只寻找一个目标,突破不是让我脱离循环吗?它让你明白了在内部for循环之外,而不是在while之外。好的。我应该在for循环之前检查目标,还是在这里检查目标是否正确?