public static <N> List<N> topologicalOrder( @NotNull Iterable<N> nodes, @NotNull Neighbors<N> neighbors, @NotNull Visited<N> visited) { TopologicalOrder<N> handler = new TopologicalOrder<N>(); for (N node : nodes) { doDfs(node, neighbors, visited, handler); } return handler.result(); }
/** * Finds the shortest path from a source to every reachable vertex in a edge weighted directed * graph. * * <p>Warning: the graph must be acyclic. * * @param graph * @param source */ public AcyclicShortestPath(EdgeWeightedDirectedGraph graph, int source) { TopologicalOrder order = new TopologicalOrder(graph); distTo = new double[graph.vertices()]; Arrays.fill(distTo, Double.POSITIVE_INFINITY); distTo[source] = 0.0; edgeTo = new int[graph.vertices()]; for (Integer vertex : order.topologicalOrder()) { for (DirectedEdge edge : graph.adjEdges(vertex)) { relax(edge); } } }