Prim idea
- Algorithms course
- Advanced
- Lesson 41/56
- 4 min
Start at a vertex, add the cheapest edge each step.
Prim idea
Prim's algorithm finds the MST by growing it from a single node. At each step, the node connected with the lowest-weight edge is added to the tree.
While Kruskal sorts edges, Prim grows the tree. Both give the same MST weight but progress differently.
Adjacency matrix
Prim works with an adjacency matrix. graph[i][j] is the edge weight between i and j; if no edge, it is 0. The matrix is symmetric.
All neighbors of a node are visible at a glance. This makes it easy to pick the lowest-weight edge.
Practice init_graph function
Write init_graph(). Return the adjacency matrix. Print it with print(init_graph()).
Starter code
def init_graph():
# Return adjacency matrixSample solution
def init_graph():
# Return adjacency matrix
return [[0, 10, 6, 5], [10, 0, 0, 15], [6, 0, 0, 4], [5, 15, 4, 0]]
print(init_graph())Expected output
[[0, 10, 6, 5], [10, 0, 0, 15], [6, 0, 0, 4], [5, 15, 4, 0]]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does Prim start?
- From a single node Correct answer
- From all edges
- From the longest path
- From a cycle
Explanation: Prim starts from a single node.
2 Edge weight
graph[0][1] = ____
graph[0][1] = 10
Explanation: 10 is right.
3 Prim idea: match the terms
| Term | Meaning |
|---|---|
graph[0][1] |
10 |
graph[0][2] |
6 |
graph[0][3] |
5 |
graph[2][3] |
4 |