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

时间:2016-03-02 00:02:26

标签: python algorithm data-structures graph floyd-warshall

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

makeRequest = function(place) {
    var req = new XMLHttpRequest();
    req.open('GET', "https://trailapi-trailapi.p.mashape.com/?limit=25&q[city_cont]=San+Luis+Obispo&radius=205", false);
    req.setRequestHeader('X-Mashape-Key', 'JwTKoEqkTbmsh3eqT0fBweCHYIAUp1h1GCbjsnkh59Bok0iqOC');
    req.onreadystatechange = function () {
        if (req.readyState === 4) {
            if (req.status >= 200 && req.status < 400) {
                var response = JSON.parse(req.responseText);
                var latLongs = response.places.map(function (key) {
                    return {lat: key.lat, lon: key.lon};
                });
                console.log("Returned");
                return latLongs;
            } else {
                alert("Failed to load " + req.status);
                return null;
            }
        }
    };
    req.send();
}

我能够获得以下的邻接矩阵:

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对角线镜像,但我不知道如何做到这一点。

我试过了:

   __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 

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

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]
我正在使用

Here is the graph

   __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 

编辑:这是完整的代码

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

1 个答案:

答案 0 :(得分:1)

我认为您的问题可以通过镜像图表字典中的所有边来解决,例如:

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