2

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

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

我在想这个:

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

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

4

1 回答 1

-4

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

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)
于 2014-11-06T06:26:05.413 回答