Day 44
Day 44: Prim's Algorithm
44/60 Days
Prim’s Algorithm#
Welcome to Day 44 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore Prim’s Algorithm, a greedy algorithm used for finding the Minimum Spanning Tree (MST) of a weighted undirected graph.
What is Prim’s Algorithm?#
Prim’s Algorithm is used to find the MST of a weighted undirected graph. An MST is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight.
How Prim’s Algorithm Works#
- Initialize a tree with a single vertex, chosen arbitrarily from the graph.
- Grow the tree by one edge: of the edges that connect the tree to vertices not yet in the tree, find the minimum-weight edge, and transfer it to the tree.
- Repeat step 2 until all vertices are in the tree.
Implementation#
Let’s implement Prim’s Algorithm in Python:
1import heapq
2
3def prim(graph):
4 # Arbitrary starting node
5 start_vertex = next(iter(graph))
6 mst = []
7 visited = set([start_vertex])
8 edges = [
9 (cost, start_vertex, to)
10 for to, cost in graph[start_vertex].items()
11 …Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating