Prim's Algorithm in Python (original) (raw)
Prim's algorithm is a **greedy algorithm used to find the Minimum Spanning Tree (MST) of a connected, undirected graph. The MST is a subset of the edges that connects all vertices in the graph with the minimum possible total edge weight.
**Input: Number of vertices: 5, Edges: [(0, 1, 2), (0, 3, 6), (1, 2, 3), (1, 3, 8), (1, 4, 5), (2, 4, 7), (3, 4, 9)]
**Output: MST Edges: [(0, 1), (1, 2), (0, 3), (1, 4)], Total weight: 16
**Explanation:
- Start with vertex 0 (any vertex can be the starting point).
- Choose the smallest edge from 0 → (0,1) with weight 2.
- From 1, pick the smallest edge → (1,2) with weight 3.
- From 0 or 1, pick the next smallest edge → (0,3) with weight 6.
- From 1, pick the next smallest edge → (1,4) with weight 5.
- All vertices are now connected, so we stop.
The MST includes edges (0, 1), (1, 2), (0, 3), and (1, 4) with a total weight of 2 + 3 + 6 + 5 = 16.
**Input: Number of vertices: 4, Edges: [(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)]
**Output: MST Edges: [(2, 3), (0, 3), (0, 1)], Total weight: 19
**Explanation: The MST includes edges (2, 3), (0, 3), and (0, 1) with a total weight of 4 + 5 + 10 = 19.
**Step 1: Determine an arbitrary vertex as the starting vertex of the MST. We pick 0 in the below diagram.
**Step 2: Follow steps 3 to 5 till there are vertices that are not included in the MST (known as fringe vertex).
**Step 3: Find edges connecting any tree vertex with the fringe vertices.
**Step 4: Find the minimum among these edges.
**Step 5: Add the chosen edge to the MST. Since we consider only the edges that connect fringe vertices with the rest, we never get a cycle.
**Step 6: Return the MST and exit