Log In Sign Up
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 #

  1. Initialize a tree with a single vertex, chosen arbitrarily from the graph.
  2. 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.
  3. 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[ …