1

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?

1 Answers1

4

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 lovely debug blog for help.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • Bro you are such a lifesaver, I was losing my hair over this, I must have checked this line at least 100 times and I didnt noticed the '1' there. Thank you so much – Helio Ramos Oct 18 '19 at 20:21