更优雅的图形实现解决方案?

时间:2018-02-21 17:15:51

标签: python

我目前正在尝试制作一个程序,该程序将使用图形数据结构,以网格形状用于寻路算法。我唯一的问题是我计划制作一个20x20网格,而一个4x4网格已经占用了大量空间。

graph = {'A': ['B', 'E'],
     'B': ['A', 'C', 'F'],
     'C': ['B', 'D', 'G'],
     'D': ['C', 'H'],
     'E': ['A', 'F', 'I'],
     'F': ['B', 'E', 'J', 'G'],
     'G': ['C', 'F', 'K', 'H'],
     'H': ['D', 'G', 'L'],
     'I': ['E', 'J', 'M'],
     'J': ['F', 'I', 'K', 'N'],
     'K': ['L', 'G', 'O', 'L'],
     'L': ['H', 'K', 'P'],
     'M': ['I', 'N'],
     'N': ['J', 'M', 'O'],
     'O': ['K', 'N', 'P'],
     'P': ['L', 'O']}

是否有更优雅的解决方案来创建我缺少的图表?

1 个答案:

答案 0 :(得分:1)

只要你知道你的网格是矩形的,你就会在邻居之间保持相同的相对距离(即上面的邻居总是X = number of columns在列表中的当前元素和下面的邻居之前后面总是X列。

如果使用节点的2D描述,则更容易看到。但是,在1D和2D描述之间进行转换(使用divmod)是一项简单的任务。一个有点复杂的例子(允许比你要求的更多)是:

from functools import partial

# Get node order from coordinates
def orderYX(y, x, Y, X):
    return y*X + x

# Get coordinates from node order
def coordinatesYX(num, Y, X):
    return divmod(num, X)

# Get the coordinates of the neigbors, based on current coordinates
def get_neighborsYX(y, x, Y, X):
    neighbors = [(y-1, x), (y+1, x), (y, x-1), (y, x+1)]
    # Also filter out neighbors outside the grid
    return [(y, x) for y, x in neighbors if (0 <= y < Y) and (0 <= x < X)]

# Special function to translate a node number to a name
# (To be able to print the graph with letters as names)
def get_name(num):
    name = []
    base = ord('A')
    Z = ord('Z') - base
    # If the number of nodes is larger than Z (25)
    # multiple letters must be used for the name
    while num > Z:
        res, rem = divmod(num, Z+1)
        num = res-1
        name.append(chr(rem + base))
    name.append(chr(num + base))
    name.reverse()
    return "".join(name)

Y = 20 # Number of rows
X = 20 # Number of columns

# Partially apply the functions, to not have to pass Y and X repeatedly
order = partial(orderYX, Y=Y, X=X)
coordinates = partial(coordinatesYX, Y=Y, X=X)
get_neighbors = partial(get_neighborsYX, Y=Y, X=X)

# Generate the graph (with named nodes)
# This may not be necessary, since the neighbors can be found when needed.
graph = {}
for num in range(Y*X):
    coord = coordinates(num)
    neighbors_coord = get_neighbors(*coord)
    neighbors = [order(y, x) for y, x in neighbors_coord]
    graph[get_name(num)] = [get_name(neighbor) for neighbor in neighbors]

在这个例子中,我还使用了partial模块中的functools,主要是因为我喜欢它。 : - )