Skip to content

Instantly share code, notes, and snippets.

@gtke
Last active December 15, 2015 15:39
Show Gist options
  • Select an option

  • Save gtke/5283443 to your computer and use it in GitHub Desktop.

Select an option

Save gtke/5283443 to your computer and use it in GitHub Desktop.
Kruskal's Algorithm for finding Minimum Spanning Tree
import java.util.ArrayList;
import java.util.Collection;
import java.util.PriorityQueue;
public class MST {
/**
* Run Kruskal's algorithm on the given graph and return the MST, return
* null if no MST exists for the graph
*
* @param g
* the graph, g will never be null
* @return the MST of the graph, null of no valid MST exists
*/
public static Collection<Edge> kruskals(Graph g) {
DisjointSets<Vertex> ds = new DisjointSets<Vertex>(g.getVertices());
PriorityQueue<Edge> pq = new PriorityQueue<Edge>();
ArrayList<Edge> mst = new ArrayList<Edge>();
for (Edge e : g.getEdgeList()) {
pq.add(e);
}
while (!pq.isEmpty() && mst.size() < g.getVertices().size() - 1) {
Edge e = pq.poll();
Vertex v = e.getV();
Vertex u = e.getU();
if (!ds.sameSet(u, v)) {
ds.merge(v, u);
mst.add(e);
}
if(g.getVertices().size()-1 == mst.size()){
return mst;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment