Problem Solving Basis - Floyd Warshall

1 minute read

Updated:

In dijkstra algorithm, we have seen single source shortest path algorithm. How about multiple sources? In other words, what if we want to know every pairs of shortest paths?

Idea

Suppose that we have V nodes, and want to figure out shortest path of any pair of those nodes, say distance from Vi to Vj.

Then, there can be possibilities as follows:

  • directly from Vi to Vj
  • take a detour. Our path is Vi to Vk and Vk to Vj

How To

Let the detour node be k.

And we are now dealing with the shortest path from Vi to Vj.

Firstly, V1 is our detour node. We compare the path distance: Vi to Vj directly and Vi to V1, and V1 to Vj

This is our first answer, and will tell the path when V1 as detour node being considered.

Secondly, V2 is our detour node. We compare the path distance: minimum distance from the first calculation, and path detouring V2.

This is our second answer, and will tell the path when V1, V2 as detour node being considered.

What would be our next step? V1, V2, …, Vk will be considered.

Complexity Analysis

Graph takes V vertices.

  • Time: There are V2 pairs, and detouring node V times considered, so V3

  • Space: V2 for adjacency matrix

Template Code

cpp: https://github.com/dongminkim0220/Problem-Solvings/blob/master/templates/cpp/floyd_warshall.cpp

Problems to Solve

Leave a comment