从网格中删除对角线

时间:2018-04-17 12:47:59

标签: arrays algorithm python-2.7 matrix graph-algorithm

我正在尝试在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类,它为节点存储x, y

1 个答案:

答案 0 :(得分:0)

不要将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