python棋盘最短路径_棋盘上的最短路径,Python

你是对的,你应该使用BFS(Breadth-first Search)。很容易看出DFS(Depth-first Search)不一定会返回最短的。但是,它仍会告诉您pawn和退出之间是否存在存在路径。

要应用BFS算法,您应该将问题视为图形而不更改问题的实际表示:

图形的顶点是2D列表中的所有元组(x,y),而不是障碍物

如果它们是2D数组中的“邻居”,则两个顶点通过边连接

这是BFS的标准实现,我们在其中替换顶点和边缘,如上所述。

def BFS(board, start):

queue = list()

queue.append(start)

visited = set()

# this keeps track of where did we get to each vertex from

# so that after we find the exit we can get back

parents = dict()

parents[start] = None

while queue:

v = queue[0]

if board[v[0]][v[1]] == 'E':

break

queue = queue[1:] # this is inefficient, an actual queue should be used

visited.add(v)

for u in neighbors(board, v):

if u not in visited:

parents[u] = v

queue.append(u)

# we found the exit, now we have to go through the parents

# up to the start vertex to return the path

path = list()

while v != None:

path.append(v)

v = parents[v]

# the path is in the reversed order so we reverse it

path = reverse(path)

return path

def neighbors(board, v):

diff = [(0, 1), (0, -1), (1, 0), (-1, 0)]

retval = list()

for d in diff:

newr = d[0] + v[0]

newc = d[1] + v[1]

if newr < 0 or newr >= len(board) or newc < 0 or newc >= len(board[0]):

continue

if board[newr][newc] == 'X':

continue

retval.append((newr, newc))

return retval

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值