Worksheet 8
Worksheet 8
Aim:
Algorithm:
Step1: Initialize the solution matrix same as the input graph matrix as a first step.
Step2: Then update the solution matrix by considering all vertices as an intermediate
vertex.
Step3: The idea is to one by one pick all vertices and updates all shortest paths which
include the picked vertex as an intermediate vertex in the shortest path.
Step5: For every pair (i, j) of the source and destination vertices respectively, there are
two possible cases.
Step6: k is not an intermediate vertex in shortest path from i to j. We keep the value of
dist[i][j] as it is.
#include <bits/stdc++.h>
using namespace std;
#define V 4
#define INF 99999
int i, j, k;
for (k = 0; k < V; k++) {
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
if (dist[i][j] > (dist[i][k] + dist[k][j])
&& (dist[k][j] != INF
&& dist[i][k] != INF))
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
printSolution(dist);
}
void printSolution(int dist[][V])
{
cout << "The following matrix shows the shortest "
"distances"
" between every pair of vertices \n";
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
cout << "INF"
<< " ";
else
cout << dist[i][j] << " ";
}
cout << endl;
}
}
int main()
{
int graph[V][V] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };
floydWarshall(graph);
return 0;
}
Output:
Learning outcomes: