π Floyd-Warshall Algorithm β Comprehensive Study Guide
The **Floyd-Warshall Algorithm** is a **dynamic programming technique** that finds the **shortest path between all pairs of vertices** in a graph.
β‘ Why Use Floyd-Warshall?
- β **Computes shortest paths between all node pairs.**
- π‘ **Works for graphs with negative weights (but no negative cycles).**
- π **Used in network routing and GPS navigation.**
- π **Can detect negative weight cycles efficiently.**
π How Does Floyd-Warshall Work?
The algorithm **iteratively improves** the shortest paths by considering intermediate vertices between each pair of nodes.
π Step-by-Step Execution
- β **Initialize** the distance matrix with given edge weights.
- π Use **three nested loops** to iteratively update the shortest distances.
- π If `dist[i][j] > dist[i][k] + dist[k][j]`, update the shortest path.
- π¨ If `dist[i][i] < 0` for any vertex, a **negative cycle** exists.
π οΈ Floyd-Warshall Algorithm Implementation
π **1. Floyd-Warshall Algorithm (O(VΒ³))**
#include
using namespace std;
const int INF = 1e9; // Large number to represent infinity
void floydWarshall(vector> &dist, int V) {
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] < INF && dist[k][j] < INF) {
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
}
}
int main() {
int V = 4;
vector> dist = {
{0, 3, INF, 5},
{2, 0, INF, 4},
{INF, 1, 0, INF},
{INF, INF, 2, 0}
};
floydWarshall(dist, V);
cout << "Shortest Distance Matrix:\n";
for (auto &row : dist) {
for (int val : row)
cout << (val == INF ? "INF" : to_string(val)) << " ";
cout << endl;
}
return 0;
}
π¨ Handling Negative Weight Cycles
The Floyd-Warshall algorithm detects **negative weight cycles** by checking the diagonal of the distance matrix.
for (int i = 0; i < V; i++) {
if (dist[i][i] < 0) {
cout << "Negative Cycle Detected!\n";
}
}
βοΈ Floyd-Warshall vs Dijkstra vs Bellman-Ford
Feature | Floyd-Warshall | Dijkstra | Bellman-Ford |
---|---|---|---|
Time Complexity | O(VΒ³) | O(V + E log V) | O(VE) |
Handles Negative Weights? | β Yes (No negative cycles) | β No | β Yes |
Shortest Path for | All Pairs | Single Source | Single Source |
Use Cases | Network Routing, Graph Theory | Navigation, AI Pathfinding | Currency Exchange, Road Networks |
β³ Time Complexity Analysis
- β **Best Case:** O(VΒ³) β Fully connected graph.
- β‘ **Worst Case:** O(VΒ³) β Sparse graph.
π Real-World Applications of Floyd-Warshall
- π‘ **Network Routing Protocols** β Finding shortest routes between all nodes.
- π **Social Network Analysis** β Measuring distances between users.
- π **AI & Game Development** β Pathfinding in multi-agent systems.
- π **GPS & Traffic Navigation Systems** β Optimal route calculations.