简体   繁体   中英

Breadth First Search - Why is My Queue being emptied?

I have code that takes a parent node from a queue, checks if it has been visited, if it hasn't, generates its children, pushes them to the queue, and repeats the loop, taking the next parent node from the queue in a FIFO fashion. Unfortunately, it seems as though I am never reaching my goal state. Is there something structurally wrong with the way I am implementing BFS? I got my desired output with this same exact code using a Stack instead of a Queue to create a DFS search. Changing "q" to a Queue (FIFO) data structure is literally the only change I have made to this code. Is there anything more I should add? The parents/children are stored as tuples, so feel free to ignore all of that work -- that doesn't seem to be where the problem lies. Also, the program breaks before isGoalState is evaluated to True, so that code doesn't seem to be contributing to the problem either. isGoalState tests whether the coordinates of a given state match the "goal" that the BFS needs to find. getSuccessors returns a list of tuples, each of which represents a child of the node.

while q:
        parent = q.pop()
        print "parent: " + str(parent)
        print str(q)
        if parent[0] in visited: continue
        visited.append(parent[0])
        if problem.isGoalState(parent[0]):
            pathList.append(parent[0])
            while actionMap[parent] is not None:
                actionList.append(actionMap[parent])
                try:
                    pathList.append(parentMap[parent])
                except KeyError:
                    break
                parent = parentMap.get(parent, None)
            actionList.reverse()
        children = problem.getSuccessors(parent[0])
        if children != []:
            for child in children:
                q.push(child)
                parentMap[child] = parent
                actionMap[child] = child[1]

Well my friends, the case is closed. Somewhere in my translation form DFS to BFS, I omitted a return statement after my while loop in the isGoalState condition had completed. That was a lot of brain racking for nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM