|
| 1 | +#include<cstdio> |
| 2 | + |
| 3 | +#define V 4 // Number of vertices in the graph |
| 4 | +#define INF 1e7 |
| 5 | + |
| 6 | +void printSolution(int dist[][V]); |
| 7 | +void floydWarshall (int graph[][V]) |
| 8 | +{ |
| 9 | + int dist[V][V], i, j, k; |
| 10 | + /* Initialize the solution matrix same as input graph matrix. Or |
| 11 | + we can say the initial values of shortest distances are based |
| 12 | + on shortest paths considering no intermediate vertex. */ |
| 13 | + for (i = 0; i < V; i++) |
| 14 | + for (j = 0; j < V; j++) |
| 15 | + dist[i][j] = graph[i][j]; |
| 16 | + /* Add all vertices one by one to the set of intermediate vertices. |
| 17 | + ---> Before start of an iteration, we have shortest distances between all |
| 18 | + pairs of vertices such that the shortest distances consider only the |
| 19 | + vertices in set {0, 1, 2, .. k-1} as intermediate vertices. |
| 20 | + ----> After the end of an iteration, vertex no. k is added to the set of |
| 21 | + intermediate vertices and the set becomes {0, 1, 2, .. k} */ |
| 22 | + for (k = 0; k < V; k++) |
| 23 | + { |
| 24 | + // Pick all vertices as source one by one |
| 25 | + for (i = 0; i < V; i++) |
| 26 | + { |
| 27 | + // Pick all vertices as destination for the |
| 28 | + // above picked source |
| 29 | + for (j = 0; j < V; j++) |
| 30 | + { |
| 31 | + // If vertex k is on the shortest path from |
| 32 | + // i to j, then update the value of dist[i][j] |
| 33 | + if (dist[i][k] + dist[k][j] < dist[i][j]) |
| 34 | + dist[i][j] = dist[i][k] + dist[k][j]; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + // Print the shortest distance matrix |
| 39 | + printSolution(dist); |
| 40 | +} |
| 41 | + |
| 42 | +void printSolution(int dist[][V]) |
| 43 | +{ |
| 44 | + printf ("The following matrix shows the shortest distances" |
| 45 | + " between every pair of vertices \n"); |
| 46 | + for (int i = 0; i < V; i++) |
| 47 | + { |
| 48 | + for (int j = 0; j < V; j++) |
| 49 | + { |
| 50 | + if (dist[i][j] == INF) |
| 51 | + printf("%7s", "INF"); |
| 52 | + else |
| 53 | + printf ("%7d", dist[i][j]); |
| 54 | + } |
| 55 | + printf("\n"); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +int main() |
| 60 | +{ |
| 61 | + // Sample graph |
| 62 | + int graph[V][V] = { {0, 5, INF, 10}, |
| 63 | + {INF, 0, 3, INF}, |
| 64 | + {INF, INF, 0, 1}, |
| 65 | + {INF, INF, INF, 0} |
| 66 | + }; |
| 67 | + floydWarshall(graph); |
| 68 | + return 0; |
| 69 | +} |
0 commit comments