Python 3D Academyবাংলা

Prim's algorithm, with a heap

🌍 In real life. A water company grows its pipe network outward from the pumping station. Each week it connects one more house: of all the pipes that could join the network to a house not yet on it, it lays the cheapest. The network is always one connected piece, and it keeps growing until every house is on it.

The idea in one sentence: Prim's algorithm grows a single tree from a start, each step adding the cheapest edge that leaves the tree, found with a heap of the edges leaving it.

Its words:

  • Prim's algorithm: build the MST by growing one tree, always by its cheapest edge to a new vertex
  • heap entry (w, v, u): a cable of price w from tree village u to village v outside; the heap gives the smallest w first
  • stale entry: like Dijkstra's (Lesson 54.2), an entry whose village joined the tree after it was pushed; it is skipped

Step by step:

  1. put the start in the tree, and push its cables
  2. pop the cheapest entry (w, v, u)
  3. if v is already in the tree, skip it; otherwise add v and the cable u–v, and push v's cables to villages still outside
  4. repeat until every village is in the tree (or the heap is empty)

Watch it grow from A. The tree's villages are green, the heap is on the right, and three stale entries are skipped on the way:

Why it works. At every step the tree's villages are on one side and the rest on the other, and Prim takes the cheapest cable crossing between them. Lesson 55.4 proves that the cheapest crossing cable is always safe. Prim and Kruskal take the same cables here, in a different order, and both total 19.

Prim or Dijkstra? The code looks almost the same. Dijkstra's heap holds a village's whole distance from the start, d + w; Prim's holds only the price w of the one cable that would join it. Dijkstra builds the tree of shortest routes from one village; Prim builds the cheapest network overall.

What it costs, by counting. A cable goes into the heap at most once, when the first of its villages joins the tree, so there are at most E pushes and E pops: O(E log E). For a dense network where every pair of places can be joined, E grows fast: 1,000 places have 499,500 possible cables: about 500,000 pushes and as many pops, each about 19 steps, some 19,000,000 in all. Without a heap, keep best[x], the cheapest cable from the tree to each place, and scan all places each round: 1,000 rounds of 1,000 = 1,000,000 steps, O(V²), better when almost every pair has a cable.

import heapq

def prim(graph, start):
    in_tree = {start}
    heap = [(w, v, start) for v, w in graph[start]]   # (price, outside village, tree village)
    heapq.heapify(heap)
    total, tree = 0, []
    while heap and len(in_tree) < len(graph):
        w, v, u = heapq.heappop(heap)       # the cheapest cable leaving the tree
        if v in in_tree:
            continue                         # stale: both ends are inside now
        in_tree.add(v)
        total += w
        tree.append((u, v, w))
        for x, wx in graph[v]:
            if x not in in_tree:
                heapq.heappush(heap, (wx, x, v))
    return total, tree

graph = {"A": [("B", 4), ("C", 3)], "B": [("A", 4), ("C", 2), ("D", 5)], "C": [("A", 3), ("B", 2), ("D", 6), ("E", 7)], "D": [("B", 5), ("C", 6), ("E", 1), ("F", 8)], "E": [("C", 7), ("D", 1), ("F", 9)], "F": [("D", 8), ("E", 9)]}
total, tree = prim(graph, "A")
print(total)
print(tree)
print(prim(graph, "F")[0])

Mistakes and edge cases.

  • no stale check: a popped entry whose village is already in the tree adds its price a second time
  • pushing d + w like Dijkstra: that builds a shortest-route tree, which can cost more in total; Prim's key is the cable's own price
  • a network that isn't connected: the heap empties before every village joins; check len(in_tree) == len(graph)
  • the start doesn't matter: any start gives a tree with the same, minimum total

Quiz

  1. What does Prim's heap hold?

    • Cables from the tree to villages outside it, cheapest first
    • Every cable, sorted by price
    • Each village's distance from the start
  2. What does this print?

    import heapq
    
    def prim(graph, start):
        in_tree = {start}
        heap = [(w, v, start) for v, w in graph[start]]   # (price, outside village, tree village)
        heapq.heapify(heap)
        total, tree = 0, []
        while heap and len(in_tree) < len(graph):
            w, v, u = heapq.heappop(heap)       # the cheapest cable leaving the tree
            if v in in_tree:
                continue                         # stale: both ends are inside now
            in_tree.add(v)
            total += w
            tree.append((u, v, w))
            for x, wx in graph[v]:
                if x not in in_tree:
                    heapq.heappush(heap, (wx, x, v))
        return total, tree
    
    print(prim({"A": [("B", 5), ("C", 1)], "B": [("A", 5), ("C", 2)], "C": [("A", 1), ("B", 2)]}, "A"))
  3. Prim's and Dijkstra's code look alike. What is the key difference?

    • Prim's heap key is the one cable's price; Dijkstra's is the whole distance from the start
    • Prim uses a deque
    • Dijkstra can't skip stale entries
  4. 1,000 places where every pair can be joined: which Prim is cheaper?

    • The array version: 1,000,000 steps, against about 19,000,000 for the heap
    • The heap version: about 20,000 steps
    • They are the same
  5. This sometimes adds the price of a cable to a village already in the tree. After which line is a check missing?

    def prim_total(graph, start):
        in_tree = {start}
        heap = [(w, v, start) for v, w in graph[start]]
        heapq.heapify(heap)
        total = 0
        while heap and len(in_tree) < len(graph):
            w, v, u = heapq.heappop(heap)
            in_tree.add(v)
            total += w
            for x, wx in graph[v]:
                if x not in in_tree:
                    heapq.heappush(heap, (wx, x, v))
        return total

Coding tasks

  1. Write prim_total(graph, start): graph maps each village to a list of (neighbour, price) cables. Return the MST's total price, grown from start with a heap, or None if some village can't be reached.

  2. Dense networks. Write prim_matrix(cost): cost[i][j] is the price of a cable between places i and j (every pair can be joined, and cost[i][i] is 0). Return the MST's total price using Prim without a heap: keep the cheapest cable from the tree to each place, and each round add the place whose cable is cheapest.