此python代码如何表示加权有向图

时间:2019-03-21 02:40:07

标签: python graph

我正在尝试使用Dijkstra算法进行一些硬件操作,但是无法可视化此输入作为图形显示的内容。代码是python。那张图怎么样?

example = [[(1, 1), (2, 2), (4, 3)], [(1, 3), (3, 4)], [(2, 3), (3, 5)], [(1, 4), (2, 5)], [], []]

1 个答案:

答案 0 :(得分:1)

我猜测列表i的第example个元素代表了所有权重为i的边。您可以将图的数据结构更改为其他形式,例如dict,其中每个键是一个节点,其值是其连接到的节点列表以及相应的宽度。

example = [[(1, 1), (2, 2), (4, 3)], [(1, 3), (3, 4)], [(2, 3), (3, 5)], [(1, 4), (2, 5)], [], []]

nodes = list(set([i for k in example for j in k for i in j ]))
arcs = [(i,example.index(j)) for j in example for i in j]

example_graph = {str(i):[] for i in nodes}
for i in arcs:
    example_graph[str(i[0][0])] += [(i[1],str(i[0][1]))]

print example_graph

这给

example_graph = {'1': [(0, '1'), (1, '3'), (3, '4')],
                 '2': [(0, '2'), (2, '3'), (3, '5')],
                 '3': [(1, '4'), (2, '5')],
                 '4': [(0, '3')], 
                 '5': []}

现在您可以实现Dijkstra算法,这是我发现的一个示例:

from heapq import heappop,heappush    

def dijkstra(s, t, neighbors):
    M = set()
    d = {s: 0}
    p = {}
    new = [(0, s)] 
    while new != []:
        dx, x = heappop(new)
        if x in M:
            continue
        M.add(x)
        for w, y in neighbors(x):
            if y in M:
                continue
            dy = dx + w
            if y not in d or d[y] > dy:
                d[y] = dy
                heappush(new, (dy, y))
                p[y] = x
    path = [t]
    x = t
    while x != s:
        x = p[x]
        path.insert(0, x)
    return d[t], path

def neighbors(s,graph=example_graph):
    return graph[s]

例如,dijkstra('1', '4', neighbors)返回(2, ['1', '3', '4'])