View Javadoc
1   /*
2    * Created on Jul 10, 2005
3    *
4    * Copyright (c) 2005, The JUNG Authors 
5    *
6    * All rights reserved.
7    *
8    * This software is open-source under the BSD license; see either
9    * "license.txt" or
10   * https://github.com/jrtom/jung/blob/master/LICENSE for a description.
11   */
12  package edu.uci.ics.jung.algorithms.shortestpath;
13  
14  import java.util.LinkedList;
15  import java.util.List;
16  import java.util.Map;
17  
18  import edu.uci.ics.jung.graph.Graph;
19  import edu.uci.ics.jung.graph.util.Pair;
20  
21  /**
22   * Utilities relating to the shortest paths in a graph.
23   */
24  public class ShortestPathUtils
25  {
26  	/**
27       * Returns a <code>List</code> of the edges on the shortest path from 
28       * <code>source</code> to <code>target</code>, in order of their
29       * occurrence on this path.  
30  	 * 
31  	 * @param graph the graph for which the shortest path is defined
32  	 * @param sp holder of the shortest path information
33  	 * @param source the vertex from which the shortest path is measured
34  	 * @param target the vertex to which the shortest path is measured
35  	 * @param <V> the vertex type
36  	 * @param <E> the edge type
37  	 * @return the edges on the shortest path from {@code source} to {@code target},
38  	 *     in the order traversed
39  	 */
40      public static <V, E> List<E> getPath(Graph<V,E> graph, ShortestPath<V,E> sp, V source, V target)
41      {
42          LinkedList<E> path = new LinkedList<E>();
43          
44          Map<V,E> incomingEdges = sp.getIncomingEdgeMap(source);
45          
46          if (incomingEdges.isEmpty() || incomingEdges.get(target) == null)
47              return path;
48          V current = target;
49          while (!current.equals(source))
50          {
51              E incoming = incomingEdges.get(current);
52              path.addFirst(incoming);
53              Pair<V> endpoints = graph.getEndpoints(incoming);
54              if(endpoints.getFirst().equals(current)) {	
55              	current = endpoints.getSecond();
56              } else {
57              	current = endpoints.getFirst();
58              }
59          }
60          return path;
61      }
62  }