PRIM'S ALGORITHM FOR Implementation in Python
MINIMUM SPANNING TREE using a Priority Queue
(Min-Heap)
(MST) Group 8
OUTLINE
- What is a Minimum Spanning Tree (MST)?
- Introduction to Prim's Algorithm
- Role of Priority Queue (Min-Heap)
- Step-by-Step Algorithm
- Python Implementation Highlights
- Example Walkthrough
- Complexity Analysis
- Applications of MST
- Conclusion
WHAT IS A MINIMUM
SPANNING TREE (MST)?
Definition:
A subset of edges connecting all nodes in a graph with the
minimum total weight.
Properties:
- No cycles
- Connects all nodes
- Minimum total weight
PRIM'S ALGORITHM
OVERVIEW
Goal: Greedily build an MST by selecting the smallest-weight edge
at each step.
Key Steps:
1. Start with an arbitrary node.
2. Grow the MST by adding the smallest edge connecting the MST
to a new node.
3. Repeat until all nodes are included.
WHY USE A PRIORITY QUEUE
(MIN-HEAP)?
Purpose: Efficiently track the smallest edge weight.
Advantages:
- O(1) time to get the minimum edge.
- O(log n) time for insertions/extractions.
Time Complexity: O(E log V) for a graph with V vertices and E
edges.
STEP-BY-STEP ALGORITHM
1. Initialize a priority queue with the starting node (weight=0).
2. Track visited nodes.
3. While the queue is not empty:
- Extract the node with the minimum weight.
- Add its unvisited neighbors to the queue with their edge
weights.
4. Repeat until all nodes are visited.
PYTHON IMPLEMENTATION
HIGHLIGHTS
import heapq # Tinoshandisa heapq kuti tishandise Min-Heap (Priority Queue)
# Tinoshandisa graph se adjacency list, graph inoratidza nzvimbo dzine ma edges uye weights (cost)
graph = {
0: [(4, 1), (8, 7)],
1: [(4, 0), (8, 2), (11, 7)],
2: [(8, 1), (7, 3), (2, 8), (4, 5)],
3: [(7, 2), (9, 4), (14, 5)],
4: [(9, 3), (10, 5)],
5: [(4, 2), (14, 3), (10, 4), (2, 6)],
# Tinoita Prim's Algorithm kuwana Minimum Spanning Tree (MST) yegirafu
def prims_algorithm(graph, start=0):
mst = [] # Inotora ma edges ari mu MST
visited = set() # Set iyo inotora nzvimbo dzatamburwa
min_heap = [
(0, start, -1)] # (cost, current_node, parent_node) Min-Heap (Priority Queue) inotanga kubva pa vertex 0
total_cost = 0 # Total cost ye MST
# Tinoenderera mberi nekutsvaga ma edges kudzamara Min-Heap yasara isina chinhu
while min_heap:
cost, current, parent = [Link](min_heap) # Tora edge ine mutengo mudiki kubva mu Min-Heap
PYTHON IMPLEMENTATION
HIGHLIGHTS
if current in visited: # Kana nzvimbo yatamburwa kare, enda kune inotevera
continue
[Link](current) # Isa nzvimbo mu visited set kuti isadzokere
if parent != -1: # Kana parent isiri -1, tiri kubatanidza node
[Link]((parent, current, cost)) # Wedzera edge ku MST
total_cost += cost # Wedzera cost ye edge ku total cost
# Tinoongorora vavakidzani venzvimbo yatiri pa (current), tichiona kana vasati vatamburwa
for edge_cost, neighbor in graph[current]:
if neighbor not in visited:
[Link](min_heap, (edge_cost, neighbor, current)) # Wedzera edge ku Min-Heap
return mst, total_cost # Dzorera MST uye total cost
# Tiri kuita Prim's Algorithm kubva pa vertex 0
mst, total_cost = prims_algorithm(graph)
# Tichadhinda MST uye total cost
print("Minimum Spanning Tree Edges:")
for u, v, cost in mst:
print(f"{u} - {v} (cost = {cost})") # Inodhinda edges dziri mu MST uye mutengo wawo
print(f"Total Cost of MST: {total_cost}") # Inodhinda total cost ye MST
6: [(2, 5), (1, 7), (6, 8)],
7: [(8, 0), (11, 1), (1, 6), (7, 8)],
8: [(2, 2), (6, 6), (7, 7)]
}
EXAMPLE WALKTHROUGH
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).
Working of Prim’s
Algorithm
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
EXAMPLE WALKTHROUGH
EXAMPLE WALKTHROUGH
EXAMPLE WALKTHROUGH
EXAMPLE WALKTHROUGH
EXAMPLE WALKTHROUGH
EXAMPLE WALKTHROUGH
EXAMPLE WALKTHROUGH
EXAMPLE WALKTHROUGH
COMPLEXITY ANALYSIS
With Min-Heap: O(E log V)
Comparison:
- Without heap: O(V²) (for adjacency matrix).
- Priority queue optimizes edge selection.
APPLICATIONS OF MST
- Network design (e.g., roads, cables).
- Cluster analysis.
- Approximation algorithms for NP-hard problems.
CONCLUSION
- Prim's algorithm efficiently finds an MST using a greedy approach.
- Min-heap reduces time complexity to O(E log V).
- Python's `heapq` simplifies priority queue implementation.
REFERENCES
1. Prim’s Algorithm Theory
- Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2009). Introduction to Algorithms
(3rd ed.). MIT Press.
- Prim, R. C. (1957). Shortest connection networks and some generalizations. Bell System
Technical Journal.
2. Python `heapq` Documentation
- Python Software Foundation. (n.d.). `heapq` — Heap queue algorithm.
[[Link]
[Link])
3. Graph Theory & MST
- Kleinberg, J., & Tardos, É. (2006). Algorithm Design. Pearson Education.
- Sedgewick, R., & Wayne, K. (2011). Algorithms (4th ed.). Addison-Wesley.
5. Graph Example Source