我有一个二维数组
我想知道从给定的某个单元格(例如
下面是一个 BFS 的脚本,但我该怎样让它接受一个二维数组作为图形以及一个起始点作为数组中的某个单元格位置,并从这个单元格前往最近的值为 2 的单元格,避免包含值为 1 的单元格,使其看起来像
arr
,其中每个单元格都有一个值为 1、2 或 3。例如,arr[0][0] = 3, arr[2][1] = 2, and arr[0][4] = 1
。我想知道从给定的某个单元格(例如
arr[5][5]
)到离它最近的值为 2 的单元格的最短路径,路径中不应包含任何值为 1 的单元格。我该如何做?下面是一个 BFS 的脚本,但我该怎样让它接受一个二维数组作为图形以及一个起始点作为数组中的某个单元格位置,并从这个单元格前往最近的值为 2 的单元格,避免包含值为 1 的单元格,使其看起来像
bfs(2darray, starting location, 2)
?def bfs(graph, start, end):
# Maintain a queue of paths
queue = []
# Push the first path into the queue
queue.append([start])
while queue:
# Get the first path from the queue
path = queue.pop(0)
# Get the last node from the path
node = path[-1]
# Path found
if node == end:
return path
# Enumerate all adjacent nodes, construct a new path and push it into the queue
for adjacent in graph.get(node, []):
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
print bfs(graph, '1', '11')