【问题标题】:Python, recursive breadth first searchPython,递归广度优先搜索
【发布时间】:2013-04-02 20:23:49
【问题描述】:

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

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 是当前位置,很明显,而 board 是,嗯,整个 board。当时的想法是它会是递归的。对于每个呼叫,我都会获取当前节点的邻居,过滤掉水(无法通过)和访问过的。然后按最接近目标的排序。 接下来,我想进行广度优先搜索。所以我会扩展所有的邻居,然后扩展他们的每个邻居等等。每个分支都将继续运行,直到没有邻居,他们将返回 None 并完成。然后最终结果是唯一返回的将是第一个到达目标的分支,即最短的。有谁知道我该怎么做?

我在想:

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

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

【问题讨论】:

  • 您的缩进遍布整个地图(混合制表符和空格绝不是一个好主意)。我已尽力解决问题,您可以验证您的帖子吗?
  • 是的,看起来不错。感谢您的修复。
  • 递归并不适合广度优先搜索。如果您进行深度优先搜索,则更有意义,因为调用堆栈可帮助您跟踪迄今为止访问过的位置。对于广度优先搜索,您希望改用队列。更多讨论请参见this related question
  • 正如@Blckknght 所说,广度优先搜索很容易通过“while-queue-not-empty-loop”(参见 python deque 结构)实现,您可以在其中推送未访问的邻居。
  • en.wikipedia.org/wiki/A*_search_algorithm

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


【解决方案1】:

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

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)

【讨论】:

  • 此伪代码为第一组邻居生成 BFS,然后运行到 DFS。
  • 在第一次扩展之后,正如杰西卡所说,它只是进入深度优先搜索!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
  • 2013-08-02
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
相关资源
最近更新 更多