
org.jgrapht.alg.spanning.KruskalMinimumSpanningTree Maven / Gradle / Ivy
The newest version!
/*
* (C) Copyright 2010-2018, by Tom Conerly 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.spanning;
import org.jgrapht.*;
import org.jgrapht.alg.interfaces.*;
import org.jgrapht.alg.util.*;
import java.util.*;
/**
* An implementation of Kruskal's minimum
* spanning tree algorithm. If the given graph is connected it computes the minimum spanning
* tree, otherwise it computes the minimum spanning forest. The algorithm runs in time $O(E \log
* E)$. This implementation uses the hashCode and equals method of the vertices.
*
* @param the graph vertex type
* @param the graph edge type
*
* @author Tom Conerly
* @since Feb 10, 2010
*/
public class KruskalMinimumSpanningTree
implements
SpanningTreeAlgorithm
{
private final Graph graph;
/**
* Construct a new instance of the algorithm.
*
* @param graph the input graph
*/
public KruskalMinimumSpanningTree(Graph graph)
{
this.graph = Objects.requireNonNull(graph, "Graph cannot be null");
}
/**
* {@inheritDoc}
*/
@Override
public SpanningTree getSpanningTree()
{
UnionFind forest = new UnionFind<>(graph.vertexSet());
ArrayList allEdges = new ArrayList<>(graph.edgeSet());
allEdges.sort(Comparator.comparingDouble(graph::getEdgeWeight));
double spanningTreeCost = 0;
Set edgeList = new HashSet<>();
for (E edge : allEdges) {
V source = graph.getEdgeSource(edge);
V target = graph.getEdgeTarget(edge);
if (forest.find(source).equals(forest.find(target))) {
continue;
}
forest.union(source, target);
edgeList.add(edge);
spanningTreeCost += graph.getEdgeWeight(edge);
}
return new SpanningTreeImpl<>(edgeList, spanningTreeCost);
}
}
// End KruskalMinimumSpanningTree.java
© 2015 - 2025 Weber Informatics LLC | Privacy Policy