From 2aef2f23b0ae8125533ca28c0622b3c114068276 Mon Sep 17 00:00:00 2001 From: Saurav Chopra Date: Sun, 17 Jul 2022 01:25:12 +0200 Subject: [PATCH] Update BellmanFordAdjacencyList.java The relaxation should be running n-1 times. We don't need to run the algo again n-1 times but only once on each edge to see if the value decreases and then we can confirm a negative cycle --- .../algorithms/graphtheory/BellmanFordAdjacencyList.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/williamfiset/algorithms/graphtheory/BellmanFordAdjacencyList.java b/src/main/java/com/williamfiset/algorithms/graphtheory/BellmanFordAdjacencyList.java index 9fe18b61c..aa20bc705 100644 --- a/src/main/java/com/williamfiset/algorithms/graphtheory/BellmanFordAdjacencyList.java +++ b/src/main/java/com/williamfiset/algorithms/graphtheory/BellmanFordAdjacencyList.java @@ -54,7 +54,7 @@ public static double[] bellmanFord(List[] graph, int V, int start) { dist[start] = 0; // For each vertex, apply relaxation for all the edges - for (int i = 0; i < V - 1; i++) + for (int i = 0; i <=V - 1; i++) for (List edges : graph) for (Edge edge : edges) if (dist[edge.from] + edge.cost < dist[edge.to]) @@ -63,7 +63,6 @@ public static double[] bellmanFord(List[] graph, int V, int start) { // Run algorithm a second time to detect which nodes are part // of a negative cycle. A negative cycle has occurred if we // can find a better path beyond the optimal solution. - for (int i = 0; i < V - 1; i++) for (List edges : graph) for (Edge edge : edges) if (dist[edge.from] + edge.cost < dist[edge.to]) dist[edge.to] = Double.NEGATIVE_INFINITY;