简体   繁体   中英

Floyd Warshall algorithm not working as intended

I'm trying to implement the Warshall algorithm in python 3 to create a matrix with the shortest distance between each point.

This is supposed to be a simple implementation, I make a matrix and fill it with the distance between each point.

However, I'm getting the wrong result, and I dont know what is the problem with my implementation.

#number of vertex (N), number of connections(M)
N, M = 4,4;
#my matrix [A,B,C] where A and B indicates a connection
#from A to B with a distance C 
A = [[0,1,2],[0,2,4],[1,3,1],[2,3,5]];
#matrix alocation
inf = float("inf");
dist = [[inf for x in range(N)] for y in range(M)];

#set distances from/to the same vertex as 0
for vertex in range(N):
    dist[vertex][vertex] = 0;
#set the distances from each vertex to the other
#they are bidirectional. 
for vertex in A:
    dist[vertex[0]][vertex[1]] = vertex[2];
    dist[vertex[1]][vertex[0]] = vertex[2];

#floyd warshall algorithm
for k in range(N):
    for i in range(N):
        for j in range(N): 
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[1][j] = dist[i][k] + dist[k][j];
print(dist);

Expected Matrix on the first index (dist[0]):

[0, 2, 4, 3]

Actual result:

[0, 2, 4, inf]

for some reason I keep getting inf instead of 3 on dist[0][3]. What am I missing?

It's a little tricky to spot, but a simple change-by-change trace of your program spots the problem:

        if dist[i][j] > dist[i][k] + dist[k][j]:
            dist[1][j] = dist[i][k] + dist[k][j];
                 ^  This should be i, not 1

You're changing the distance from node 1 to the target node; rather than from the source node. Your resulting distance matrix is

[0, 2, 4, 3]
[2, 0, 6, 1]
[4, 6, 0, 5]
[3, 1, 5, 0]

See this lovelydebug blog for help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM