diff --git a/Recipe search app/Floyd-Warshall Algorithm.cpp b/Recipe search app/Floyd-Warshall Algorithm.cpp new file mode 100644 index 00000000..56c16fc1 --- /dev/null +++ b/Recipe search app/Floyd-Warshall Algorithm.cpp @@ -0,0 +1,54 @@ +#include +#include + +using namespace std; + +const int INF = 99999; // Infinity or a sufficiently large value to represent absence of an edge + +void floydWarshall(vector>& graph, int V) { + // Initialize the distance matrix with the graph's adjacency matrix + vector> dist(V, vector(V)); + + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + dist[i][j] = graph[i][j]; + } + } + + // Find the shortest paths + for (int k = 0; k < V; k++) { + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + if (dist[i][k] + dist[k][j] < dist[i][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + } + + // Print the shortest path distances + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + if (dist[i][j] == INF) { + cout << "INF\t"; + } else { + cout << dist[i][j] << "\t"; + } + } + cout << endl; + } +} + +int main() { + int V = 4; // Number of vertices + vector> graph = { + {0, 3, INF, 7}, + {8, 0, 2, INF}, + {5, INF, 0, 1}, + {2, INF, INF, 0} + }; + + floydWarshall(graph, V); + + return 0; +}