/*
 * (C) Copyright 2007-2016, by Vinayak R Borkar and Contributors.
 *
 * JGraphT : a free Java graph-theory library
 *
 * This program and the accompanying materials are dual-licensed under
 * either
 *
 * (a) the terms of the GNU Lesser General Public License version 2.1
 * as published by the Free Software Foundation, or (at your option) any
 * later version.
 *
 * or (per the licensee's choosing)
 *
 * (b) the terms of the Eclipse Public License v1.0 as published by
 * the Eclipse Foundation.
 */
package org.jgrapht.alg;

import org.jgrapht.DirectedGraph;
import org.jgrapht.Graphs;
import org.jgrapht.experimental.dag.DirectedAcyclicGraph;
import org.jgrapht.graph.SimpleDirectedGraph;
import org.jgrapht.traverse.TopologicalOrderIterator;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Constructs the transitive closure of the input graph.
 *
 * @author Vinayak R. Borkar
 * @since May 5, 2007
 */
public class TransitiveClosure
{
    /**
     * Singleton instance.
     */
    public static final TransitiveClosure INSTANCE = new TransitiveClosure();

    /**
     * Private Constructor.
     */
    private TransitiveClosure()
    {
    }

    /**
     * Computes the transitive closure of the given graph.
     *
     * @param graph - Graph to compute transitive closure for.
     * @param <V> the graph vertex type
     * @param <E> the graph edge type
     */
    public <V, E> void closeSimpleDirectedGraph(SimpleDirectedGraph<V, E> graph)
    {
        Set<V> vertexSet = graph.vertexSet();

        Set<V> newEdgeTargets = new HashSet<>();

        // At every iteration of the outer loop, we add a path of length 1
        // between nodes that originally had a path of length 2. In the worst
        // case, we need to make floor(log |V|) + 1 iterations. We stop earlier
        // if there is no change to the output graph.

        int bound = computeBinaryLog(vertexSet.size());
        boolean done = false;
        for (int i = 0; !done && (i < bound); ++i) {
            done = true;
            for (V v1 : vertexSet) {
                newEdgeTargets.clear();

                for (E v1OutEdge : graph.outgoingEdgesOf(v1)) {
                    V v2 = graph.getEdgeTarget(v1OutEdge);
                    for (E v2OutEdge : graph.outgoingEdgesOf(v2)) {
                        V v3 = graph.getEdgeTarget(v2OutEdge);

                        if (v1.equals(v3)) {
                            // Its a simple graph, so no self loops.
                            continue;
                        }

                        if (graph.getEdge(v1, v3) != null) {
                            // There is already an edge from v1 ---> v3, skip;
                            continue;
                        }

                        newEdgeTargets.add(v3);
                        done = false;
                    }
                }

                for (V v3 : newEdgeTargets) {
                    graph.addEdge(v1, v3);
                }
            }
        }
    }

    /**
     * Computes floor(log_2(n)) + 1
     */
    private int computeBinaryLog(int n)
    {
        assert n >= 0;

        int result = 0;
        while (n > 0) {
            n >>= 1;
            ++result;
        }

        return result;
    }

    /**
     * Computes the transitive closure of a directed acyclic graph in O(n*m)
     *
     * @param graph - Graph to compute transitive closure for.
     * @param <V> the graph vertex type
     * @param <E> the graph edge type
     */
    public <V, E> void closeDirectedAcyclicGraph(DirectedAcyclicGraph<V, E> graph)
    {
        List<V> orderedItems = getTopologicallyOrderedVertices(graph);
        for (int i = 0; i < orderedItems.size(); i++) {
            V vertex = orderedItems.get(orderedItems.size() - 1 - i);
            for (V successor : Graphs.successorListOf(graph, vertex)) {
                for (V closureVertex : Graphs.successorListOf(graph, successor)) {
                    graph.addEdge(vertex, closureVertex);
                }
            }
        }
    }

    private static <V, E> List<V> getTopologicallyOrderedVertices(DirectedGraph<V, E> graph) {
        List<V> orderedItems = new ArrayList<>(graph.vertexSet().size());
        TopologicalOrderIterator<V, E> iterator = new TopologicalOrderIterator<>(graph);
        while(iterator.hasNext()) {
            orderedItems.add(iterator.next());
        }
        return orderedItems;
    }
}

// End TransitiveClosure.java

@@ -530,42 +530,8 @@
 g;%0A%0A
-import org.jgrapht.DirectedGraph;%0A
 impo
@@ -734,20 +734,21 @@
 il.Array
-List
+Deque
 ;%0Aimport
@@ -758,23 +758,21 @@
 va.util.
-HashSet
+Deque
 ;%0Aimport
@@ -782,19 +782,22 @@
 va.util.
-Lis
+HashSe
 t;%0Aimpor
@@ -3602,36 +3602,37 @@
 )%0A    %7B%0A        
-List
+Deque
 %3CV%3E orderedItems
@@ -3630,19 +3630,75 @@
 ered
-Items = get
+Vertices = new ArrayDeque%3C%3E(graph.vertexSet().size());%0A        new 
 Topo
@@ -3708,101 +3708,85 @@
 ical
-ly
 Order
-edVertices(graph);%0A        for (int i = 0; i %3C orderedItems.size(); i++) %7B%0A   
+Iterator%3C%3E(graph).forEachRemaining(orderedVertices::addFirst);%0A%0A
         
  V v
@@ -3781,17 +3781,21 @@
         
- 
+for (
 V vertex
@@ -3799,17 +3799,17 @@
 tex 
-=
+:
  ordered
 Item
@@ -3808,47 +3808,19 @@
 ered
-Items.get(orderedItems.size() - 1 - i);
+Vertices) %7B
 %0A   
@@ -4082,394 +4082,8 @@
  %7D%0A%0A
-    private static %3CV, E%3E List%3CV%3E getTopologicallyOrderedVertices(DirectedGraph%3CV, E%3E graph) %7B%0A        List%3CV%3E orderedItems = new ArrayList%3C%3E(graph.vertexSet().size());%0A        TopologicalOrderIterator%3CV, E%3E iterator = new TopologicalOrderIterator%3C%3E(graph);%0A        while(iterator.hasNext()) %7B%0A            orderedItems.add(iterator.next());%0A        %7D%0A        return orderedItems;%0A    %7D%0A
 %7D%0A%0A/

refactor transitive closure for DAGs