1 25 41 package org.jgrapht.alg; 42 43 import java.util.*; 44 45 import org.jgrapht.*; 46 47 48 53 public class BellmanFordShortestPath<V, E> 54 { 55 56 58 61 protected Graph<V, E> graph; 62 63 66 protected V startVertex; 67 68 private BellmanFordIterator<V, E> iter; 69 70 73 private int nMaxHops; 74 75 private int passNumber; 76 77 79 86 public BellmanFordShortestPath(Graph<V, E> graph, V startVertex) 87 { 88 this(graph, startVertex, graph.vertexSet().size() - 1); 89 } 90 91 99 public BellmanFordShortestPath( 100 Graph<V, E> graph, 101 V startVertex, 102 int nMaxHops) 103 { 104 this.startVertex = startVertex; 105 this.nMaxHops = nMaxHops; 106 this.graph = graph; 107 108 this.passNumber = 1; 109 } 110 111 113 119 public double getCost(V endVertex) 120 { 121 lazyCalculate(); 122 123 assertGetPath(endVertex); 124 125 return this.iter.getPathElement(endVertex).getCost(); 126 } 127 128 134 public List<E> getPathEdgeList(V endVertex) 135 { 136 assertGetPath(endVertex); 137 138 lazyCalculate(); 139 140 if (this.iter.getPathElement(endVertex) == null) { 141 return null; 142 } 143 144 return createPath(endVertex); 145 } 146 147 private void assertGetPath(V endVertex) 148 { 149 if (endVertex.equals(this.startVertex)) { 150 throw new IllegalArgumentException ( 151 "The end vertex is the same as the start vertex!"); 152 } 153 154 if (!this.graph.containsVertex(endVertex)) { 155 throw new IllegalArgumentException ( 156 "Graph must contain the end vertex!"); 157 } 158 } 159 160 167 private List<E> createPath(V endVertex) 168 { 169 AbstractPathElement<V, E> pathElement = 170 this.iter.getPathElement(endVertex); 171 172 return pathElement.createEdgeListPath(); 173 } 174 175 private void lazyCalculate() 176 { 177 if (this.iter == null) { 178 this.iter = 179 new BellmanFordIterator<V, E>(this.graph, this.startVertex); 180 } 181 182 for ( 185 ; 186 (this.passNumber <= this.nMaxHops) && this.iter.hasNext(); 187 this.passNumber++) { 188 this.iter.next(); 189 } 190 } 191 192 203 public static <V, E> List<E> findPathBetween( 204 Graph<V, E> graph, 205 V startVertex, 206 V endVertex) 207 { 208 BellmanFordShortestPath<V, E> alg = 209 new BellmanFordShortestPath<V, E>( 210 graph, 211 startVertex); 212 213 return alg.getPathEdgeList(endVertex); 214 } 215 } 216 | Popular Tags |