📖 Scenario: You are working as a network engineer. You need to connect several computers with cables. Each cable has a cost. Your goal is to connect all computers with the least total cost.
🎯 Goal: Build a program that finds the minimum total cost to connect all computers using Prim's algorithm for the Minimum Spanning Tree.
📋 What You'll Learn
Create a graph using an adjacency list with exact edges and weights
Create a vector to track visited nodes
Implement Prim's algorithm core logic using a priority queue
Print the total minimum cost after running the algorithm
💡 Why This Matters
🌍 Real World
Network design, connecting computers or cities with minimum cable or road cost.
💼 Career
Useful for software engineers working on network optimization, infrastructure planning, and graph algorithms.
Progress0 / 4 steps
1
Create the graph as an adjacency list
Create a variable called graph as a vector of vectors of tuples. The graph should have 5 nodes (0 to 4). Add these edges with weights exactly: 0 - 1 (2), 0 - 3 (6), 1 - 2 (3), 1 - 3 (8), 1 - 4 (5), 2 - 4 (7), 3 - 4 (9). Each edge should be added in both directions (undirected graph).
DSA Rust
Hint
Use a Vec> where each inner vector holds tuples of (neighbor_node, weight).
2
Create a visited vector to track nodes
Create a mutable vector called visited of type Vec with 5 elements, all set to false. This will track which nodes have been visited.
DSA Rust
Hint
Use vec![false; 5] to create a vector with 5 false values.
3
Implement Prim's algorithm core logic
Use std::collections::BinaryHeap as a min-heap by pushing tuples with negative weights. Create a mutable variable total_cost set to 0. Start from node 0 by pushing (0, 0) into the heap. While the heap is not empty, pop the smallest edge. If the node is not visited, mark it visited and add the edge weight to total_cost. Then push all edges from this node to the heap if their destination is not visited.
DSA Rust
Hint
Use a max-heap with negative weights to simulate a min-heap. Remember to mark nodes visited before adding their edges.
4
Print the total minimum cost
Write a println! statement to print the total_cost variable.
DSA Rust
Hint
Use println!("{}", total_cost); to display the final minimum cost.
Practice
(1/5)
1. What is the main goal of Prim's Algorithm in graph theory?
easy
A. To detect cycles in a graph
B. To find the minimum spanning tree connecting all vertices with minimum total edge weight
C. To find the shortest path between two vertices
D. To sort vertices in topological order
Solution
Step 1: Understand Prim's Algorithm purpose
Prim's Algorithm builds a tree that connects all vertices with the smallest possible sum of edge weights.
Step 2: Compare with other graph algorithms
Shortest path algorithms find paths, cycle detection finds loops, and topological sort orders vertices, which are different goals.
Final Answer:
To find the minimum spanning tree connecting all vertices with minimum total edge weight -> Option B
Quick Check:
Prim's Algorithm = Minimum Spanning Tree [OK]
Hint: Prim's builds minimum spanning tree by adding cheapest edges [OK]
Common Mistakes:
Confusing Prim's with shortest path algorithms
Thinking it detects cycles
Mixing it with topological sorting
2. Which Rust data structure is best suited to efficiently pick the next minimum edge in Prim's Algorithm?
easy
A. Vec (Vector)
B. LinkedList
C. HashMap
D. BinaryHeap (Min-Heap)
Solution
Step 1: Identify operation needed in Prim's Algorithm
Prim's needs to repeatedly select the edge with the smallest weight efficiently.
Step 2: Choose data structure for minimum extraction
A BinaryHeap (min-heap) allows quick access to the smallest element, unlike Vec or LinkedList which require scanning.
Final Answer:
BinaryHeap (Min-Heap) -> Option D
Quick Check:
Min-Heap = Efficient minimum edge selection [OK]
Hint: Use min-heap to get smallest edge fast in Prim's [OK]
Common Mistakes:
Using Vec which is slow for minimum extraction
Choosing HashMap which is for key-value, not min extraction
Using LinkedList which is inefficient for this
3. What is the output of the following Rust code snippet implementing Prim's Algorithm on a graph with edges [(0,1,2), (1,2,3), (0,2,1)] starting from vertex 0?
let edges = vec![(0,1,2), (1,2,3), (0,2,1)];
// Prim's MST total weight calculation
// Output the total weight of MST
medium
A. 3
B. 5
C. 4
D. 6
Solution
Step 1: List edges and weights
Edges: (0-1)=2, (1-2)=3, (0-2)=1. Start from vertex 0.
Step 2: Build MST using Prim's Algorithm
Start at 0, pick smallest edge (0-2)=1, then pick next smallest connecting edge (0-1)=2. Total weight = 1 + 2 = 3.
Step 3: Check if all vertices connected
Vertices 0,1,2 connected with edges (0-2) and (0-1). Edge (1-2) with weight 3 is not needed.
Final Answer:
3 -> Option A
Quick Check:
MST weight = 1 + 2 = 3 [OK]
Hint: Pick smallest edges connecting new vertices stepwise [OK]
Common Mistakes:
Adding all edges instead of MST edges
Choosing heavier edges first
Not starting from given start vertex
4. Identify the bug in this Rust snippet implementing Prim's Algorithm:
let mut visited = vec![false; n];
let mut heap = BinaryHeap::new();
heap.push(Reverse((0, 0)));
while let Some(Reverse((cost, u))) = heap.pop() {
if visited[u] { continue; }
visited[u] = true;
for &(v, w) in &graph[u] {
if !visited[v] {
heap.push(Reverse((w, v)));
}
}
}
medium
A. The heap should be a max-heap, not min-heap
B. The heap should store (cost, vertex) as (u, cost) instead
C. The visited check is missing before pushing neighbors
D. The graph adjacency list should store (vertex, weight) not (weight, vertex)
Solution
Step 1: Analyze visited check placement
Currently, neighbors are pushed without checking if visited, causing duplicates in heap.
Step 2: Fix by checking visited before pushing neighbors
Adding a visited check before pushing neighbors avoids unnecessary heap entries and improves efficiency.
Final Answer:
The visited check is missing before pushing neighbors -> Option C
Quick Check:
Check visited before pushing neighbors to heap [OK]
Hint: Check visited before pushing neighbors to avoid duplicates [OK]
Common Mistakes:
Ignoring visited check before pushing neighbors
Confusing min-heap with max-heap
Swapping vertex and weight in tuples
5. Given a weighted undirected graph with vertices 0 to 4 and edges: