tom | 2e1f071 | 2014-08-29 13:32:00 -0700 | [diff] [blame] | 1 | package org.onlab.graph; |
| 2 | |
| 3 | /** |
| 4 | * Bellman-Ford graph search algorithm for locating shortest-paths in |
| 5 | * directed graphs that may contain negative cycles. |
| 6 | */ |
| 7 | public class BellmanFordGraphSearch<V extends Vertex, E extends Edge<V>> |
| 8 | extends AbstractGraphPathSearch<V, E> { |
| 9 | |
| 10 | @Override |
| 11 | public Result<V, E> search(Graph<V, E> graph, V src, V dst, |
| 12 | EdgeWeight<V, E> weight) { |
| 13 | checkArguments(graph, src, dst); |
| 14 | |
| 15 | // Prepare the graph search result. |
| 16 | DefaultResult result = new DefaultResult(src, dst); |
| 17 | |
| 18 | // The source vertex has cost 0, of course. |
| 19 | result.updateVertex(src, null, 0.0, true); |
| 20 | |
| 21 | int max = graph.getVertexes().size() - 1; |
| 22 | for (int i = 0; i < max; i++) { |
| 23 | // Relax, if possible, all egress edges of the current vertex. |
| 24 | for (E edge : graph.getEdges()) { |
| 25 | if (result.hasCost(edge.src())) { |
| 26 | result.relaxEdge(edge, result.cost(edge.src()), weight); |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // Remove any vertexes reached by traversing edges with negative weights. |
| 32 | for (E edge : graph.getEdges()) { |
| 33 | if (result.hasCost(edge.src())) { |
| 34 | if (result.relaxEdge(edge, result.cost(edge.src()), weight)) { |
| 35 | result.removeVertex(edge.dst()); |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // Finally, but the paths on the search result and return. |
| 41 | result.buildPaths(); |
| 42 | return result; |
| 43 | } |
| 44 | |
| 45 | } |