Exemple #1
0
 /**
  * Initializes a new edge-weighted digraph that is a deep copy of {@code G}.
  *
  * @param  G the edge-weighted digraph to copy
  */
 public EdgeWeightedDigraph(EdgeWeightedDigraph G) {
     this(G.V());
     this.E = G.E();
     for (int v = 0; v < G.V(); v++)
         this.indegree[v] = G.indegree(v);
     for (int v = 0; v < G.V(); v++) {
         // reverse so that adjacency list is in same order as original
         Stack<DirectedEdge> reverse = new Stack<DirectedEdge>();
         for (DirectedEdge e : G.adj[v]) {
             reverse.push(e);
         }
         for (DirectedEdge e : reverse) {
             adj[v].add(e);
         }
     }
 }
Exemple #2
0
    /**
     * Determines whether the edge-weighted digraph {@code G} has a
     * topological order and, if so, finds such a topological order.
     * @param G the digraph
     */
    public TopologicalX(EdgeWeightedDigraph G) {

        // indegrees of remaining vertices
        int[] indegree = new int[G.V()];
        for (int v = 0; v < G.V(); v++) {
            indegree[v] = G.indegree(v);
        }

        // initialize 
        ranks = new int[G.V()]; 
        order = new Queue<Integer>();
        int count = 0;

        // initialize queue to contain all vertices with indegree = 0
        Queue<Integer> queue = new Queue<Integer>();
        for (int v = 0; v < G.V(); v++)
            if (indegree[v] == 0) queue.enqueue(v);

        while (!queue.isEmpty()) {
            int v = queue.dequeue();
            order.enqueue(v);
            ranks[v] = count++;
            for (DirectedEdge e : G.adj(v)) {
                int w = e.to();
                indegree[w]--;
                if (indegree[w] == 0) queue.enqueue(w);
            }
        }

        // there is a directed cycle in subgraph of vertices with indegree >= 1.
        if (count != G.V()) {
            order = null;
        }

        assert check(G);
    }