From 810560cabea696cc3bc6d8d9a27b67346790c154 Mon Sep 17 00:00:00 2001
From: Bruno Freitas Tissei <bft15@inf.ufpr.br>
Date: Tue, 5 Mar 2019 22:47:57 -0300
Subject: [PATCH] Add Bellman-Ford

Signed-off-by: Bruno Freitas Tissei <bft15@inf.ufpr.br>
---
 algorithms/graph/bellman_ford.cpp | 34 +++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
 create mode 100644 algorithms/graph/bellman_ford.cpp

diff --git a/algorithms/graph/bellman_ford.cpp b/algorithms/graph/bellman_ford.cpp
new file mode 100644
index 0000000..d8a3e1d
--- /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];
+}
-- 
GitLab