DSA — Prim's Algorithm
What is Prim's Algorithm?
Finds MST by growing from a starting vertex, always adding the cheapest edge.
import heapq
def prim(graph, start=0):
n = len(graph)
visited = [False] * n
mst = []
pq = [(0, start, -1)]
while pq:
weight, u, parent = heapq.heappop(pq)
if visited[u]:
continue
visited[u] = True
if parent != -1:
mst.append((parent, u, weight))
for v, w in graph[u]:
if not visited[v]:
heapq.heappush(pq, (w, v, u))
return mst
Time Complexity
| Operation | Complexity |
|---|---|
| Using priority queue | O(E log V) |
| Using adjacency matrix | O(V²) |
Applications
- Network design
- Cable wiring
- Road network planning
Mini Practice
- Implement Prim's algorithm
- Find minimum spanning tree
- Compare with Kruskal's
- Handle disconnected graphs
Up Next
Continue with Topological Sort — ordering directed graphs.
Related Topics
Frequently Asked Questions about Prim's Algorithm
What is Prim's Algorithm in DSA?
Prim's Algorithm is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Prim's Algorithm?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Prim's Algorithm.
Why is Prim's Algorithm important in DSA?
Prim's Algorithm is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.