org.jungrapht.samples.util.SpanningTreeAdapter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jungrapht-visualization-samples Show documentation
Show all versions of jungrapht-visualization-samples Show documentation
Sample programs using Graph Visualization.
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