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

Graph initialisation using dictionaries for floyd algorithm on undirected graphs?

我想知道如何在无向图上实现 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]

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

 __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