protected Graph<String, DefaultWeightedEdge> createWithBias(boolean negate) { Graph<String, DefaultWeightedEdge> g; double bias = 1; if (negate) { // negative-weight edges are being tested, so only a directed graph // makes sense g = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class); bias = -1; } else { // by default, use an undirected graph g = new SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class); } g.addVertex(V1); g.addVertex(V2); g.addVertex(V3); g.addVertex(V4); g.addVertex(V5); e12 = Graphs.addEdge(g, V1, V2, bias * 2); e13 = Graphs.addEdge(g, V1, V3, bias * 3); e24 = Graphs.addEdge(g, V2, V4, bias * 5); e34 = Graphs.addEdge(g, V3, V4, bias * 20); e45 = Graphs.addEdge(g, V4, V5, bias * 5); e15 = Graphs.addEdge(g, V1, V5, bias * 100); return g; }
/** Calculates the matrix of all shortest paths, but does not populate the paths map. */ private void lazyCalculateMatrix() { if (d != null) { // already done return; } int n = vertices.size(); // init the backtrace matrix backtrace = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(backtrace[i], -1); } // initialize matrix, 0 d = new double[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(d[i], Double.POSITIVE_INFINITY); } // initialize matrix, 1 for (int i = 0; i < n; i++) { d[i][i] = 0.0; } // initialize matrix, 2 Set<E> edges = graph.edgeSet(); for (E edge : edges) { V v1 = graph.getEdgeSource(edge); V v2 = graph.getEdgeTarget(edge); int v_1 = vertices.indexOf(v1); int v_2 = vertices.indexOf(v2); d[v_1][v_2] = graph.getEdgeWeight(edge); if (!(graph instanceof DirectedGraph<?, ?>)) { d[v_2][v_1] = graph.getEdgeWeight(edge); } } // run fw alg for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { double ik_kj = d[i][k] + d[k][j]; if (ik_kj < d[i][j]) { d[i][j] = ik_kj; backtrace[i][j] = k; } } } } }
private void shortestPathRecur(List<E> edges, int v_a, int v_b) { int k = backtrace[v_a][v_b]; if (k == -1) { E edge = graph.getEdge(vertices.get(v_a), vertices.get(v_b)); if (edge != null) { edges.add(edge); } } else { shortestPathRecur(edges, v_a, k); shortestPathRecur(edges, k, v_b); } }
private GraphPath<V, E> getShortestPathImpl(V a, V b) { int v_a = vertices.indexOf(a); int v_b = vertices.indexOf(b); List<E> edges = new ArrayList<E>(); shortestPathRecur(edges, v_a, v_b); // no path, return null if (edges.size() < 1) { return null; } double weight = 0.; for (E e : edges) { weight += graph.getEdgeWeight(e); } GraphPathImpl<V, E> path = new GraphPathImpl<V, E>(graph, a, b, edges, weight); return path; }
public FloydWarshallShortestPaths(Graph<V, E> graph) { this.graph = graph; this.vertices = new ArrayList<V>(graph.vertexSet()); }