blob: caf8019f288064d493ebc509bbda0c2342df867d [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
Thomas Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
Thomas Vachuska24c849c2014-10-27 09:53:05 -070015 */
tom2e1f0712014-08-29 13:32:00 -070016package org.onlab.graph;
17
18/**
19 * Bellman-Ford graph search algorithm for locating shortest-paths in
20 * directed graphs that may contain negative cycles.
21 */
22public class BellmanFordGraphSearch<V extends Vertex, E extends Edge<V>>
23 extends AbstractGraphPathSearch<V, E> {
24
25 @Override
26 public Result<V, E> search(Graph<V, E> graph, V src, V dst,
27 EdgeWeight<V, E> weight) {
28 checkArguments(graph, src, dst);
29
30 // Prepare the graph search result.
31 DefaultResult result = new DefaultResult(src, dst);
32
33 // The source vertex has cost 0, of course.
34 result.updateVertex(src, null, 0.0, true);
35
36 int max = graph.getVertexes().size() - 1;
37 for (int i = 0; i < max; i++) {
38 // Relax, if possible, all egress edges of the current vertex.
39 for (E edge : graph.getEdges()) {
40 if (result.hasCost(edge.src())) {
41 result.relaxEdge(edge, result.cost(edge.src()), weight);
42 }
43 }
44 }
45
46 // Remove any vertexes reached by traversing edges with negative weights.
47 for (E edge : graph.getEdges()) {
48 if (result.hasCost(edge.src())) {
49 if (result.relaxEdge(edge, result.cost(edge.src()), weight)) {
50 result.removeVertex(edge.dst());
51 }
52 }
53 }
54
55 // Finally, but the paths on the search result and return.
56 result.buildPaths();
57 return result;
58 }
59
60}