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.



									$INF = 99999;

function PrintResult($distance, $verticesCount)
{
	global $INF;
	
	echo "<pre>" . "Shortest distances between every pair of vertices:" . "<br/>";

	for ($i = 0; $i < $verticesCount; ++$i)
	{
		for ($j = 0; $j < $verticesCount; ++$j)
		{
			if ($distance[$i][$j] == $INF)
				echo str_pad("INF", 7);
			else
				echo str_pad($distance[$i][$j], 7);
		}

		echo "<br/>";
	}
	echo  "</pre>";
}

function FloydWarshall($graph, $verticesCount)
{
	$distance = array();

	for ($i = 0; $i < $verticesCount; ++$i)
		for ($j = 0; $j < $verticesCount; ++$j)
			$distance[$i][$j] = $graph[$i][$j];

	for ($k = 0; $k < $verticesCount; ++$k)
	{
		for ($i = 0; $i < $verticesCount; ++$i)
		{
			for ($j = 0; $j < $verticesCount; ++$j)
			{
				if ($distance[$i][$k] + $distance[$k][$j] < $distance[$i][$j])
					$distance[$i][$j] = $distance[$i][$k] + $distance[$k][$j];
			}
		}
	}

	PrintResult($distance, $verticesCount);
}
								


Example

									$graph = array(
	array(0, 5, $INF, 10),
	array($INF, 0, 3, $INF),
	array($INF, $INF, 0, 1),
	array($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