你是对的,你应该使用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