Skip to content

Commit 73192ca

Browse files
author
Lord-of-Algorithms
committed
Terminate Kruskal's algorithm when MST reaches V-1 edges
1 parent 72b3d9f commit 73192ca

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

src/graph/mst/kruskal/KruskalMstMain.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,10 @@ public int compare(Edge edge1, Edge edge2) {
7272
if (uf.find(edge.getSource()) != uf.find(edge.getDestination())) {
7373
mst.add(edge);
7474
uf.union(edge.getSource(), edge.getDestination());
75+
if (mst.size() == vertices.size() - 1) {
76+
// Stop when MST is complete
77+
break;
78+
}
7579
}
7680
}
7781
return mst;

0 commit comments

Comments
 (0)