我正在尝试用Dijkstra算法做一些hw,但我很难将这个输入可视化为一个图。代码是python。这怎么是一个图表呢?
example = [[(1, 1), (2, 2), (4, 3)], [(1, 3), (3, 4)], [(2, 3), (3, 5)], [(1, 4), (2, 5)], [], []]发布于 2019-03-21 14:51:13
我猜list example的第th个元素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这给了我们
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'])
https://stackoverflow.com/questions/55273008
复制相似问题