# Floyd–Warshall algorithm on undirected graph

I am referring to the algorithm from the Wikipedia page on the Floyd–Warshall algorithm.

In case of undirected graphs should I change the assignment statement inside the if condition to

dist[i][j] = dist[j][i] = dist[i][k] + dist[k][j]


or they are equivalent?

• What do you think? – Raphael Jun 2 '14 at 23:50
• I thought that they are equivalent. – aghost Jun 3 '14 at 4:15
• "They"? Hint: Can you ever have dist[i][j] != dist[j][i] in an undirected graph? – Raphael Jun 3 '14 at 6:30
• You can save slightly less then half of memory (strictly saying (n * (n - 1)) / 2) for undirected graph by trade-off with slightly complicated indexing (and, therefore, runtime). – Tomilov Anatoliy Jan 9 '17 at 12:35

Every undirected graph can be represented as directed graph by replacing every edge $(i,j)$ with 2 edges $(i,j); (j,i)$. And if you're running Floyd–Warshall algorithm on such directed graph - it would work correctly, as always.

• It does not work correctly if the undirected graph has a negative edge. – xskxzr Mar 23 '19 at 15:59

Actually this algorithm is so amazing that it works for both directed and undirected graph.

Only one thing you should keep in mind while storing distances at (i,j) you should do the same for (j,i).

graph(i,j) = graph(j,i) = distance

Rest algorithm will work fine and you only need to do:

dist[i][j] = dist[i][k] + dist[k][j]

• Not really so amazing -- an undirected graph is just a special case of a directed graph in which the edge relation is symmetric. – David Richerby Jun 22 '16 at 10:00

I think for undirected graph the Floyd-Warshall algorithm can be optimized. The speedup should be 2.

            for(INTTYPE k = 0; k < num_nodes; k++) {
for(INTTYPE i = 0; i < num_nodes; i++) {
INTTYPE distki = (k<i)?dist[k][i]:dist[i][k];
if(k == i || distki == INF) {
continue;
}

for(INTTYPE j = i+1; j < num_nodes; j++) {
INTTYPE distkj = (k<j)?dist[k][j]:dist[j][k];
if(k == j || i == j || distkj == INF) {
continue;
}
WEIGHTTYPE via = distki + distkj;
if(via < dist[i][j]) {
dist[i][j] = via;
prev[i][j] = k;
}
}
}
}


The optimization comes in the inner-most loop(for(INTTYPE j = i+1; j < num_nodes; j++){ }). It only calculates one half of the matrix.