从网格中删除对角线
Remove diagonals from a grid
我正在尝试在 python 中创建一个高度为 5 宽度为 10 的图表。到目前为止,我有这段代码构建了一个图形,该图形具有到对角线的边以及图中的上、左、右和下边:
def construct_graph(data):
# initialize all of the astar nodes
nodes = [[ANode(x, y) for y in range(data['height'])] for x in range(data['width'])]
graph = {}
# make a graph with child nodes
for x, y in product(range(data['width']), range(data['height'])):
node = nodes[x][y]
graph[node] = []
for i, j in product([-1, 0, 1], [-1, 0, 1]):
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
如何修改上面的函数只创建上、左、右、下链接?
注意:ANode只是一个普通的python class,它为一个节点存储x, y
。
不要将 product
用于内部循环,只需指定您想要的邻居:
def construct_graph(data):
# initialize all of the astar nodes
nodes = [[ANode(x, y) for y in range(data['height'])] for x in range(data['width'])]
graph = {}
# make a graph with child nodes
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
我正在尝试在 python 中创建一个高度为 5 宽度为 10 的图表。到目前为止,我有这段代码构建了一个图形,该图形具有到对角线的边以及图中的上、左、右和下边:
def construct_graph(data):
# initialize all of the astar nodes
nodes = [[ANode(x, y) for y in range(data['height'])] for x in range(data['width'])]
graph = {}
# make a graph with child nodes
for x, y in product(range(data['width']), range(data['height'])):
node = nodes[x][y]
graph[node] = []
for i, j in product([-1, 0, 1], [-1, 0, 1]):
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
如何修改上面的函数只创建上、左、右、下链接?
注意:ANode只是一个普通的python class,它为一个节点存储x, y
。
不要将 product
用于内部循环,只需指定您想要的邻居:
def construct_graph(data):
# initialize all of the astar nodes
nodes = [[ANode(x, y) for y in range(data['height'])] for x in range(data['width'])]
graph = {}
# make a graph with child nodes
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