gpt4 book ai didi

python - 在无向图上使用 floyd 算法的字典进行图初始化?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:00:52 25 4
gpt4 key购买 nike

我想知道如何在无向图上实现 floyd。有了这个实现,

for k in graph:
for i in graph:
for j in graph:
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
pred[i][j] = pred[k][j]

我能够得到邻接矩阵:

   __0 __1 __2 __3 __4 

0| 0 28 38 33 63

1| inf 0 10 60 44

2| inf inf 0 50 80

3| inf inf inf 0 30

4| inf inf inf inf 0

这是一个有向图。很好,但我希望邻接矩阵显示无向图。据我了解,对于无向图,这些路径应该沿 0 对角线进行镜像,但我不确定该怎么做。

我试过:

for k in graph:
for i in graph:
for j in graph:
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
dist[j][i] = dist[i][k] + dist[k][j]
pred[i][j] = pred[k][j]

但我的图表结果是错误的,看起来算法正在通过不需要的边到达所需的顶点。

   __0 __1 __2 __3 __4 

0| 0 48 38 93 63

1| 48 0 110 60 44

2| 38 110 0 110 80

3| 93 60 110 0 30

4| 63 inf 80 inf 0

Here is the graph我正在使用:

{0 : {1:28, 3:33},
1 : {2:10, 4:44},
2 : {3:50},
3 : {4:30},
4 : {}}

编辑:这是完整的代码

import ast

def floyd(graph):
dist = {}
pred = {}

for u in graph:
dist[u] = {}
pred[u] = {}

for v in graph:
dist[u][v] = float('INF')
pred[u][v] = -1
dist[u][u] = 0
for z in graph[u]:
dist[u][z] = graph[u][z]
pred[u][z] = u

for k in graph:
for i in graph:
for j in graph:
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]

return dist, pred

graph = {}
graph = ast.literal_eval(open("file2.txt").read())
print graph

dist, pred = floyd(graph)

print " ",
for j in dist: print "__" + str(j),
print "\n"
for i in dist:
print str(i) + "|",
for v in dist: print " %s" % (dist[i][v]),
print "\n"

最佳答案

我认为只需镜像图形字典中的所有边即可解决您的问题,例如:

graph = {0 : {1:28, 3:33},
1 : {2:10, 4:44},
2 : {3:50},
3 : {4:30},
4 : {}}
# Mirror all edges
for u in graph:
for v in graph[u]:
if not u in graph[v]:
graph[v][u] = graph[u][v]

这是将输入设置为无向图的最简单方法(尽管显然现在如果您随后编辑/删除边则需要更加小心)。当我将其插入您的代码时,我得到:

 __0__1__2__3__4

0| 0 28 38 33 63

1| 28 0 10 60 44

2| 38 10 0 50 54

3| 33 60 50 0 30

4| 63 44 54 30 0

关于python - 在无向图上使用 floyd 算法的字典进行图初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35736040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com