@@ -0,0 +1,2433 @@
+package me.alivecode.algs4;%0A%0Aimport edu.princeton.cs.algs4.In;%0Aimport edu.princeton.cs.algs4.StdOut;%0A%0A/**%0A * The %7B@code Topological%7D class a data type for%0A * computing the topological order of a directed acyclic graph.%0A */%0Apublic class Topological %7B%0A    private Iterable%3CInteger%3E order;%0A    private int%5B%5D rank;%0A%0A    /**%0A     * Computes the topological order of the specified directed graph.%0A     *%0A     * @param dag the directed graph.%0A     */%0A    public Topological(Digraph dag) %7B%0A        DirectedCycle cycle = new DirectedCycle(dag);%0A%0A        if (!cycle.hasCycle()) %7B%0A            DepthFirstOrder finder = new DepthFirstOrder(dag);%0A            order = finder.reversePostOrder();%0A            int i = 0;%0A            rank = new int%5Bdag.V()%5D;%0A            for(int v: order) %7B%0A                rank%5Bv%5D = i++;%0A            %7D%0A        %7D%0A    %7D%0A%0A    /**%0A     * Returns the order of the specified vertex %7B@code v%7D.%0A     *%0A     * @param v the vertex.%0A     * @return the order of vertex %7B@code v%7D if the specified%0A     * directed graph is acyclic, or -1 otherwise%0A     */%0A    public int rank(int v) %7B%0A        validateVertex(v);%0A        if (hasOrder()) %7B%0A            return rank%5Bv%5D;%0A        %7D%0A        return -1;%0A    %7D%0A%0A    private void validateVertex(int v) %7B%0A        if (!hasOrder()) return; // make sure rank has been initialized.%0A        if (v %3C 0 %7C%7C v %3E= rank.length) throw new IllegalArgumentException();%0A    %7D%0A%0A    /**%0A     * Is the specified directed graph has topological order?%0A     *%0A     * @return %7B@code true%7D if the specified directed graph has topological order,%0A     * or %7B@code false%7D otherwise.%0A     */%0A    public boolean hasOrder() %7B%0A        return order != null;%0A    %7D%0A%0A    /**%0A     * Returns vertices in topological order.%0A     *%0A     * @return vertices in topological order%0A     * if the specified directed graph has topological order,%0A     * or %7B@code null%7D otherwise.%0A     */%0A    public Iterable%3CInteger%3E order() %7B%0A        return order;%0A    %7D%0A%0A    // unit test code.%0A    public static void main(String%5B%5D args) %7B%0A        In in = new In(args%5B0%5D);%0A        Digraph dag = new Digraph(in);%0A        Topological order = new Topological(dag);%0A        if (order.hasOrder()) %7B%0A            StdOut.print(%22topological order:%22);%0A            for(int v : order.order()) %7B%0A                StdOut.print(%22 %22 + v);%0A            %7D%0A            StdOut.println();%0A        %7D%0A        else %7B%0A            StdOut.println(%22has no order%22);%0A        %7D%0A%0A    %7D%0A%7D%0A

Add Topological class.