#include <stdio.
h>
#include <stdlib.h>
#include <limits.h>
void floydWarshall(int **graph, int **split, int v)
{
int i, j, k;
for (k = 0; k < v; k++)
{
for (i = 0; i < v; i++)
{
for (j = 0; j < v; j++)
{
if (graph[i][k] != INT_MAX && graph[k][j] != INT_MAX && graph[i][k]
+ graph[k][j] < graph[i][j])
{
graph[i][j] = graph[i][k] + graph[k][j];
split[i][j] = k;
}
}
}
}
}
void printSolution(int **graph, int v)
{
for (int i = 0; i < v; i++)
{
for (int j = 0; j < v; j++)
{
if (graph[i][j] == INT_MAX)
{
printf("INF\t");
}
else
{
printf("%d\t", graph[i][j]);
}
}
printf("\n");
}
}
int main()
{
int i, j, v = 0;
FILE *fp = fopen("fw_graph.txt", "r");
if (fp != NULL)
{
fscanf(fp, "%d", &v);
int **graph = (int **)malloc(v * sizeof(int *));
int **split = (int **)malloc(v * sizeof(int *));
for (i = 0; i < v; i++)
{
graph[i] = (int *)malloc(v * sizeof(int));
split[i] = (int *)calloc(v,sizeof(int));
}
printf("Adjacency Graph:-\n");
for (i = 0; i < v; i++)
{
for (j = 0; j < v; j++)
{
fscanf(fp, "%d", &graph[i][j]);
if (graph[i][j] == -1)
{
graph[i][j] = INT_MAX;
printf("INF\t");
}
else
{
printf("%d\t", graph[i][j]);
}
split[i][j]--;
}
printf("\n");
}
fclose(fp);
floydWarshall(graph, split, v);
printf("\nShortest distances between every pair of vertices:-\n");
printSolution(graph, v);
printf("\nSplit Matrix:-\n");
printSolution(split, v);
printf("\nShortest path between vertices:-\n");
for (i = 0; i < v; i++)
{
for (j = 0; j < v; j++)
{
if (i != j)
{
printf("From %d to %d:", i, j);
if(graph[i][j] != INT_MAX)
{
printf("\tShortest distance: %d\t", graph[i][j]);
printf("Shortest Path: %d", i);
int k = i;
while (split[k][j] != -1)
{
printf(" -> %d", split[k][j]);
k = split[k][j];
}
printf(" -> %d\n", j);
}
else
{
printf("\tShortest distance: INF\n");
}
}
}
}
}
else
printf("File not found!\n");
return 0;
}