首页 > 解决方案 > 同时搜索两个双端队列中的节点并打印队列中的值 - Python 3

问题描述

我有一个广度优先搜索算法的代码。

在此处输入图像描述

根据算法的最后 3 行,我们必须在执行任何进一步操作之前检查两个队列中的子状态是否已经可用。在我的代码中,我必须使用 BFS 算法在迷宫中搜索从起点到终点的路径。我创建了一个节点,用于保存网格位置的状态、动作、路径和父节点。代码如下:

#class to initialize node
class Node:
    state = []
    actions = []
    parent = []
    path = 0
    
    def __init__(self, state, actions, parent, path):
        self.state = state
        self.actions = actions
        self.parent = parent
        self.path = path

在算法函数中,我将节点从起点添加到 Python 中的双端队列。但在添加之前,我必须检查 child.state 不应处于前沿或探索队列的条件。我在代码中的条件无限运行。如下:

def bfs_search(maze_size, start_point, end_point, grid_values, number_of_grids):
    
    #code for creating first node and adding to queue
 
    
    while True:
            #here we have the code to break the loop if queue gets empty and then finding the child 
             pointer and creating child notes

            #this condition does not execute as it should
            if child_node.state not in frontier and child_node.state not in explored:
                if child_node.state == end_point:
                    goal = True
                    explored.appendleft(child_node)
                    break
                else:
                    frontier.appendleft(child_node)

我还想在测试代码以检查节点是否被附加到队列时打印附加到队列的元素。

标签: pythonbreadth-first-searchdeque

解决方案


推荐阅读