Last active
February 6, 2020 11:01
-
-
Save bitsnaps/7283026b655c270fcd0bafeac6a03bfa to your computer and use it in GitHub Desktop.
Bellman-Ford Algorithm using Edge List with Groovy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * An implementation of the Bellman-Ford algorithm. The algorithm finds the shortest path between a | |
| * starting node and all other nodes in the graph. The algorithm also detects negative cycles. | |
| * Original Source: https://github.com/williamfiset/Algorithms/blob/master/src/main/java/com/williamfiset/algorithms/graphtheory/BellmanFordEdgeList.java | |
| */ | |
| @groovy.transform.Canonical | |
| class Edge { | |
| int from, to | |
| double cost | |
| } | |
| def bellman = {List<Edge> edges, int v, start -> | |
| double[] dist = ([Double]*v)*.newInstance(Double.POSITIVE_INFINITY) | |
| dist[start] = 0 | |
| relaxedAnEdge = true | |
| for (i = 0; (i < v - 1) && relaxedAnEdge; i++){ | |
| relaxedAnEdge = false | |
| edges.each { e -> | |
| if (dist[e.from] + e.cost < dist[e.to]){ | |
| dist[e.to] = dist[e.from] + e.cost | |
| relaxedAnEdge = true | |
| } | |
| } | |
| } | |
| relaxedAnEdge = true | |
| for (i = 0; (i < v - 1) && relaxedAnEdge; i++){ | |
| relaxedAnEdge = false | |
| edges.each { e -> | |
| if (dist[e.from] + e.cost < dist[e.to]){ | |
| dist[e.to] = Double.NEGATIVE_INFINITY | |
| relaxedAnEdge = true | |
| } | |
| } | |
| } | |
| dist | |
| } | |
| int V = 9, start = 0 | |
| List<Edge> edges = [ | |
| new Edge(0, 1, 1), | |
| new Edge(1, 2, 1), | |
| new Edge(2, 4, 1), | |
| new Edge(4, 3, -3), | |
| new Edge(3, 2, 1), | |
| new Edge(1, 5, 4), | |
| new Edge(1, 6, 4), | |
| new Edge(5, 6, 5), | |
| new Edge(6, 7, 4), | |
| new Edge(5, 7, 3) | |
| ] | |
| double[] d = bellman(edges, V, start) | |
| V.times { int i -> | |
| printf("The cost to get from node %d to %d is %.2f\n", start, i, d[i]) | |
| } | |
| /* Output: | |
| The cost to get from node 0 to 0 is 0,00 | |
| The cost to get from node 0 to 1 is 1,00 | |
| The cost to get from node 0 to 2 is -Infinity | |
| The cost to get from node 0 to 3 is -Infinity | |
| The cost to get from node 0 to 4 is -Infinity | |
| The cost to get from node 0 to 5 is 5,00 | |
| The cost to get from node 0 to 6 is 5,00 | |
| The cost to get from node 0 to 7 is 8,00 | |
| The cost to get from node 0 to 8 is Infinity | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment