import java.util.ArrayList; /** Instances of this class are immutable objects representing weighted directed graphs (with no loops or multiple edges). Vertices are represented by ints, as are edge weights. Infinite edge weights are represented by the value Integer.MAX_VALUE. The methods of this class are not guaranteed to work correctly if the absolute values of path costs exceed this value, or if the matrices fail to satisfy the constraints required for correct behavior of the underlying algorithm. */ public class Graph { private int n; // the number of vertices private int[][] adjacency; // the (weighted) adjacency matrix /** This constructor builds a graph with a given adjacency matrix, except that (1) entries on the main diagonal are required to be 0 (2) rows with more elements than there are rows are truncated, and (3) rows with fewer elements than there are rows are padded with trailing zeros. */ public Graph(int[][] array) { n = array.length; adjacency = new int[n][n]; for (int i=0; i reversedPath = bellmanFordWithDestination(source, dest); int[] path = new int[reversedPath.size()]; int index = path.length - 1; for (Integer i : reversedPath) { path[index] = i; index--; } return path; } /** Constructs a string representing the (weighted) adjacency matrix of the graph, as a 2-dimensional table. Infinite values are represented as asterisks @return the string */ // Note the use of System.getProperty("line.separator") // for platform independence. public String toString() { StringBuffer sb = new StringBuffer(); for (int i=0; i bellmanFordWithDestination( int source, int dest) { final int ILLEGAL_VERTEX = -1; int[] d = new int[n]; int[] pred = new int[n]; // the predecessor vertices for (int i=0; i path = new ArrayList(); int v = dest; while (v != ILLEGAL_VERTEX) { path.add(v); v = pred[v]; } return path; } //////// PRIVATE METHODS FOR MULTIPLE ALL-PAIRS ALGORITHMS /////// /** Constructs an adjacency matrix for a graph whose edge cost for a vertex pair (i,j) represents the cost of a cheapest path of length at most r+s between i and j, given a graph that does the same for paths of length r and a graph that does the same for paths of length s. This method can be thought of as a variant of matrix multiplication. It is associative but not commutative. @param g the given graph @return the new graph */ private static int[][] gtProduct(int[][] adj1, int[][] adj2) { int size = adj1.length; int[][] returnArray = new int[size][size]; for (int i=0; i