1. Repeated Bellman-Ford from Every Vertex
Intuition
Execute Bellman-Ford V times, treating each vertex i as the source to construct the V x V distance matrix.
Algorithm
- Convert adjacency matrix into an edge list.
- For each vertex i from 0 to V - 1:
- Run Bellman-Ford with source = i.
- Copy resulting distance array into row i of output matrix.
- Return the V x V matrix.
#include <iostream>#include <vector> using namespace std; const int INF = 1e8; void floydWarshallBellmanFord(vector<vector<int>>& matrix) { int V = matrix.size(); vector<vector<int>> edges; for (int i = 0; i < V; ++i) { for (int j = 0; j < V; ++j) { if (i != j && matrix[i][j] != -1) { edges.push_back({i, j, matrix[i][j]}); } } } for (int src = 0; src < V; ++src) { vector<int> dist(V, INF); dist[src] = 0; for (int i = 0; i < V - 1; ++i) { for (const auto& e : edges) { int u = e[0], v = e[1], w = e[2]; if (dist[u] != INF && dist[u] + w < dist[v]) { dist[v] = dist[u] + w; } } } for (int j = 0; j < V; ++j) { matrix[src][j] = (dist[j] >= INF) ? -1 : dist[j]; } }} int main() { vector<vector<int>> matrix = { {0, 2, -1, -1}, {1, 0, 3, -1}, {-1, -1, 0, -1}, {3, 5, 4, 0} }; floydWarshallBellmanFord(matrix); cout << "Shortest Matrix via Repeated Bellman-Ford:" << endl; for (const auto& row : matrix) { for (int d : row) cout << d << " "; cout << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(V^2 * E) ≈ O(V^4) in dense graphs - Space complexity:
O(V^2)