Minimum Spanning Tree with Prim's Algorithm

medium
Unit 9 · Graphs II0/2 to milestone

Prim's algorithm grows a minimum spanning tree from a start vertex, always adding the cheapest edge that connects a new vertex. With a heap it runs in O(E log V).

Implement prim(n, edges, start=0) for an undirected weighted graph on nodes 0..n-1 with edges (u, v, w). Return (total_weight, tree_edges), where tree_edges is the sorted list of (min(u, v), max(u, v), w) edges in the tree. Raise ValueError if the graph is disconnected.

Then implement mst_unique(n, edges): True if the MST is unique. One way: the MST is unique if, for every tree edge, removing it and finding the best replacement (the cheapest non-tree edge reconnecting the two parts) always costs more than the edge removed.

#graphs#greedy#heaps2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Minimum Spanning Tree with Prim's Algorithm · TechGradify