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.



									/*****Please include following header files*****/
// stdio.h
/***********************************************/

#define VERTICES_COUNT 4
#define INF 99999

void Print(int distance[][VERTICES_COUNT])
{
	printf("Shortest distances between every pair of vertices: \n");

	for (int i = 0; i < VERTICES_COUNT; ++i)
	{
		for (int j = 0; j < VERTICES_COUNT; ++j)
		{
			if (distance[i][j] == INF)
				printf("%7s", "INF");
			else
				printf("%7d", distance[i][j]);
		}

		printf("\n");
	}
}

void FloydWarshall(int graph[][VERTICES_COUNT])
{
	int distance[VERTICES_COUNT][VERTICES_COUNT];

	for (int i = 0; i < VERTICES_COUNT; i++)
		for (int j = 0; j < VERTICES_COUNT; j++)
			distance[i][j] = graph[i][j];

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

	Print(distance);
}
								


Example

									int graph[VERTICES_COUNT][VERTICES_COUNT] = {
	{ 0,   5,  INF, 10 },
	{ INF, 0,   3, INF },
	{ INF, INF, 0,   1 },
	{ INF, INF, INF, 0 }
};

FloydWarshall(graph);
								


Output

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