Floyd–Warshall Algorithm

Floyd–Warshall algorithm, also known as Floyd's algorithm, the Roy–Warshall algorithm, the Roy–Floyd algorithm, or the WFI algorithm, is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles). A single execution of the algorithm will find the lengths (summed weights) of the shortest paths between all pairs of vertices, though it does not return details of the paths themselves. Versions of the algorithm can also be used for finding the transitive closure of a relation R, or (in connection with the Schulze voting system) widest paths between all pairs of vertices in a weighted graph.



									Public Const INF As Integer = 99999

Private Shared Sub Print(distance As Integer(,), verticesCount As Integer)
	Console.WriteLine("Shortest distances between every pair of vertices:")

	For i As Integer = 0 To verticesCount - 1
		For j As Integer = 0 To verticesCount - 1
			If distance(i, j) = INF Then
				Console.Write("INF".PadLeft(7))
			Else
				Console.Write(distance(i, j).ToString().PadLeft(7))
			End If
		Next

		Console.WriteLine()
	Next
End Sub

Public Shared Sub FloydWarshall(graph As Integer(,), verticesCount As Integer)
	Dim distance As Integer(,) = New Integer(verticesCount - 1, verticesCount - 1) {}

	For i As Integer = 0 To verticesCount - 1
		For j As Integer = 0 To verticesCount - 1
			distance(i, j) = graph(i, j)
		Next
	Next

	For k As Integer = 0 To verticesCount - 1
		For i As Integer = 0 To verticesCount - 1
			For j As Integer = 0 To verticesCount - 1
				If distance(i, k) + distance(k, j) < distance(i, j) Then
					distance(i, j) = distance(i, k) + distance(k, j)
				End If
			Next
		Next
	Next

	Print(distance, verticesCount)
End Sub
								


Example

									Dim graph As Integer(,) = {{0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0}}

FloydWarshall(graph, 4)
								


Output

									Shortest distances between every pair of vertices:
      0      5      8      9
    INF      0      3      4
    INF    INF      0      1
    INF    INF    INF      0