我猜列表example的第i元素代表所有宽度为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
这给了
^{pr2}$
现在您可以实现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'])