Prim's and Kruskal's algorithm

user1687035 picture user1687035 · Nov 9, 2012 · Viewed 10.9k times · Source

Prim's and Kruskal's algorithm both produce the minimum spanning tree. According to the cut property, the total cost of the tree will be the same for these algorithms, but is it possible that these two algorithms give different MST with the same total cost, given that we choose it in alphabetic order when faced with multiple choices. for example, we compare max(source,dest), for edges A->B and B->C, we compare A from A->B and B from B->C.

Thank you

Answer

jma127 picture jma127 · Nov 13, 2012

Assuming that your comparator handles the case where both edges are equal in cost and have the same max(source, dest) character, it will never declare any two edges equal. For there to be the possibility of multiple MSTs, at least two edges in the graph must be equal. Therefore, the MST is unique, and both Prim's and Kruskal's algorithm will return the same result.

On the other hand, if your comparator declares the edges A->B (cost 1) and A->C (cost 1) equal, than there is a possibility that the algorithms will generate different MSTs, depending on which edge they consider first (A->B or A->C).