Bellman Ford
Implementation
// Time: O(VE)
// Space: O(V)
vector<int> bellmanFord(vector<vector<int>>& edges, int V, int src) {
vector<int> dist(N, INT_MAX);
dist[src] = 0;
for (int i = 1; i < V; ++i) { // try to use all the edges to relax V-1 times.
for (auto &e : edges) {
int u = e[0], v = e[1], w = e[2];
if (dist[u] == INT_MAX) continue;
dist[v] = min(dist[v], dist[u] + w); // Try to use this edge to relax the cost of `v`.
}
}
return dist;
}Problems
Reference
Last updated