</>
Skip to content
DSA lessons (44/55)

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

OperationComplexity
Using priority queueO(E log V)
Using adjacency matrixO(V²)

Applications

  • Network design
  • Cable wiring
  • Road network planning

Mini Practice

  1. Implement Prim's algorithm
  2. Find minimum spanning tree
  3. Compare with Kruskal's
  4. 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.