不使用
product
对于内部循环,只需指定所需的邻居:
def construct_graph(data):
nodes = [[ANode(x, y) for y in range(data['height'])] for x in range(data['width'])]
graph = {}
for x, y in product(range(data['width']), range(data['height'])):
node = nodes[x][y]
graph[node] = []
for i, j in [(-1, 0), (0, -1), (0, 1), (1, 0)]:
if not (0 <= x + i < data['width']): continue
if not (0 <= y + j < data['height']): continue
if [x+i,y+j] in data['obstacle']: continue
graph[nodes[x][y]].append(nodes[x+i][y+j])
return graph, nodes