在下面的函数中,“graph”是由1、0和“two”(分别表示障碍物、开阔区域和目标)组成的二维网格列表,“start”是开始搜索的起点。在
def bfs(图形,开始):fringe = [[start]]
# Special case: start == goal
if start.val == 'g':
return [start]
start.visited = True
# Calculate width and height dynamically. We assume that "graph" is dense.
width = len(graph[0])
height = len(graph)
# List of possible moves: up, down, left, right.
moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while fringe:
# Get first path from fringe and extend it by possible moves.
path = fringe.pop(0)
#print path
node = path[-1]
pos = node.pos
# Using moves list (without all those if's with +1, -1 etc.) has huge benefit:
# moving logic is not duplicated. It will save you from many silly errors.