All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jungrapht.samples.util.SpanningTreeAdapter Maven / Gradle / Ivy

The newest version!
package org.jungrapht.samples.util;

import org.jgrapht.Graph;
import org.jgrapht.alg.interfaces.SpanningTreeAlgorithm;
import org.jgrapht.alg.spanning.PrimMinimumSpanningTree;
import org.jgrapht.graph.AsUndirectedGraph;
import org.jgrapht.graph.DefaultGraphType;
import org.jgrapht.graph.builder.GraphTypeBuilder;

public class SpanningTreeAdapter {

  /**
   * @param graph input graph, directed or undirected
   * @param  vertex type
   * @param  edge type
   * @return a directed acyclic graph that contains all vertices and edges from the minimum spanning
   *     tree of the input graph
   */
  public static  Graph getSpanningTree(Graph graph) {

    if (graph.getType().isDirected()) {
      // make a non-directed version
      graph = new AsUndirectedGraph(graph);
    }
    SpanningTreeAlgorithm prim = new PrimMinimumSpanningTree<>(graph);
    SpanningTreeAlgorithm.SpanningTree tree = prim.getSpanningTree();
    Graph newGraph = GraphTypeBuilder.forGraphType(DefaultGraphType.dag()).buildGraph();

    for (E edge : tree.getEdges()) {
      newGraph.addVertex(graph.getEdgeSource(edge));
      newGraph.addVertex(graph.getEdgeTarget(edge));
      newGraph.addEdge(graph.getEdgeSource(edge), graph.getEdgeTarget(edge), edge);
    }
    return newGraph;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy