Python,递归广度优先搜索

时间:2013-04-02 20:23:49

标签: python path-finding breadth-first-search

我试图在网格上找到最短路径(元组列表列表) 到目前为止我已经得到了这个:

def planPath(self, x, y, goal, board):
    visited = []
    path = []
    def pathFinder(curr):
        visited.append(curr)
        neighbors = None
        if curr == goal:
            visited.append(curr)
            return curr
        neighbors = [neighbor for neighbor in curr.neighbors if type(neighbor) is not Land.Water and neighbor not in visited]
        neighbors.sort(key=lambda neighbor:  abs(neighbor.location[0] - goal.location[0]) + abs(neighbor.location[1] - goal.location[1]) + abs(neighbor.elevation - goal.elevation), reverse=False)

x,y是当前位置,显而易见,而且电路板是整个电路板。这个想法是它将是递归的。对于每次调用,我都会得到当前节点的邻居,过滤掉水(不可移动)和访问过的。然后按最接近目标排序。 接下来我想通过并进行广度优先搜索。所以我将扩展所有邻居,然后扩展他们的邻居等等。每个分支都会继续,直到他们没有邻居,他们将返回None并完成。然后最终结果是唯一一个返回的将是到达目标的第一个brach,即最短的。有谁知道我怎么能做到这一点?

我在想这个:

for neighbor in neighbors:
    next = pathFinder(neighbor)
    if next:
        visited.append(cure)
        return curr
    else: return None

但是,如果我错了,请纠正我,但这会导致深度优先搜索,而不是广度。

1 个答案:

答案 0 :(得分:0)

以下是可以帮助您的伪代码

BFS(v)
    let neighbors be the set of all neighbours of vertex v
    for neighbor in neighbors:
        if neighbor is not visited:
            visit neighbour
    for neighbor in neighbors:
        recurisvely call BFS(neighbor)