diff --git a/algorithms/graph/bellman_ford.cpp b/algorithms/graph/bellman_ford.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8a3e1d148bda0acfdb6d25cc11267d9239ef850 --- /dev/null +++ b/algorithms/graph/bellman_ford.cpp @@ -0,0 +1,34 @@ +/** + * Bellman-Ford + * + * Complexity (Time): O(V*E) + * Complexity (Space): O(V + E) + */ + +struct edge { + int u, v, w; +}; + +int dist[MAX]; +vector<edge> graph; + +// Returns distance between s and d in a graph with V vertices +// using bellman_ford +int bellman_ford(int s, int d, int V) { + mset(dist, inf); + dist[s] = 0; + + // Iterate through all edges V times computing the shortest distance + // to all vertices from s + for (int i = 0; i < V; ++i) + for (auto e : graph) + if (dist[e.u] != inf && dist[e.u] + e.w < dist[e.v]) + dist[e.v] = dist[e.u] + e.w; + + // Check for negative cycles, return -inf if there is one + for (auto e : graph) + if (dist[e.u] != inf && dist[e.u] + w < dist[e.v]) + return -inf; + + return dist[d]; +}