com.salesforce.jgrapht.alg.spanning.KruskalMinimumSpanningTree Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of AptSpringProcessor Show documentation
Show all versions of AptSpringProcessor Show documentation
This project contains the apt processor that implements all the checks enumerated in @Verify. It is a self contained, and
shaded jar.
/*
* (C) Copyright 2010-2017, 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 com.salesforce.jgrapht.alg.spanning;
import java.util.*;
import com.salesforce.jgrapht.*;
import com.salesforce.jgrapht.alg.interfaces.*;
import com.salesforce.jgrapht.alg.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());
Collections.sort(
allEdges, (edge1, edge2) -> Double
.valueOf(graph.getEdgeWeight(edge1)).compareTo(graph.getEdgeWeight(edge2)));
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