Summary - Prim
- Algorithms course
- Advanced
- Lesson 44/56
- 4 min
Run Prim and print the MST weight in a mini task.
Summary - Prim
In this group you learned Prim, which finds the MST by growing from a single node. Adjacency matrix, min_key and visited set combine into the solution.
Now you will write a function that brings all pieces together. This summary unites the group's concepts in a single piece of code.
Practice mst_total function
Write mst_total(graph). min_key is given; each round pick the lowest node, update neighbors, sum. Print 19 with print(mst_total(init_graph())).
Starter code
def init_graph():
# Return adjacency matrix
return [[0, 10, 6, 5], [10, 0, 0, 15], [6, 0, 0, 4], [5, 15, 4, 0]]
def min_key(keys, visited):
# Find unvisited index with smallest keys
best = float('inf')
idx = -1
for i in range(len(keys)):
if not visited[i] and keys[i] < best:
best = keys[i]
idx = i
return idx
def mst_total(graph):
# Find total MST weightSample solution
def init_graph():
# Return adjacency matrix
return [[0, 10, 6, 5], [10, 0, 0, 15], [6, 0, 0, 4], [5, 15, 4, 0]]
def min_key(keys, visited):
# Find unvisited index with smallest keys
best = float('inf')
idx = -1
for i in range(len(keys)):
if not visited[i] and keys[i] < best:
best = keys[i]
idx = i
return idx
def mst_total(graph):
# Find total MST weight
n = len(graph)
keys = [float('inf')] * n
keys[0] = 0
visited = [False] * n
total = 0
for _ in range(n):
u = min_key(keys, visited)
visited[u] = True
total += keys[u]
for v in range(n):
if graph[u][v] and not visited[v] and graph[u][v] < keys[v]:
keys[v] = graph[u][v]
return total
print(mst_total(init_graph()))Expected output
19
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the common output of Prim and Kruskal?
- Edge list
- Node order
- Cycle count
- MST weight Correct answer
Explanation: Both return the MST weight.
2 Visited update
visited[____] = True
visited[u] = True
Explanation: u is right.
3 Summary - Prim: match the terms
| Term | Meaning |
|---|---|
init_graph |
Matrix |
min_key |
Selection |
prim |
MST |
keys |
Cost |