Floyd-Warshall’s algorithm is a modification of Warshall’s algorithm that allows it to be applicable for weighted graphs. It can be used to solve the all-pairs shortest path problem (ASPP) via dynamic programming. It uses the transitive closure of a graph to achieve this.

Does not work on negative cycles!

Negative weights are not necessarily a problem, but negative cycles are. • These trigger arbitrarily low values for the paths involved. • Floyd’s algorithm can be adapted to detect negative cycles (by looking if diagonal values become negative)#todo

Process

Let be the graph which we are trying to solve ASPP for.

  1. Initialise a square matrix, (using a 2-dimensional array) of size . Let be this matrix.
  2. Convert to an weighted adjacency matrix of by a nested for loop.
    1. For every node in , loop through every node in and if an edge with weight exists, set . Else, set it to 0.
  3. Return . If is not 0, then there exists a path from to .

As a recurrence relation, this can be expressed as:

Let be an adjacency matrix.

Pseudocode

Algorithm Floyd_Warshall(G):
	dist ← |V| x |V| array
	
	//Initialise the dist matrix
	For vertex v in G do: #O(|V|)
		dist[v][v] ← 0
	End do
	For edge u-v with weight w in G do: #O(|E|)
		dist[u][v] ← w
	End do
	//Relaxation: Find check if a shorter path exist via intermediate path k
	For k from 1 to |V| do: #O(|V|)
		From i from 1 to |V| do: #O(|V|)
			From j from 1 to |V| do: #O(|V|)
				If dist[i][k] + dist[k][j] < dist[i][j] then:
					dist[i][j] ← dist[i][k] + dist[k][j]
				End if
			End do
		End do
	End do
	Return dist
	
End Algorithm

Time Complexity

The time complexity is easy to comprehend because of a closed for loop. The triple nested for loop evaluates to three times, giving a time complexity of:

Case ScenarioInput DescriptionGrowth FunctionAsymptoticNotes
Worst
Time complexity is same for every case
Average
Best

Visualisation

FloydWarshall_ManimCE_v0.17.3 2

Implementation

Floyd-Warshall