📖 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 without any loops.
🎯 Goal: Build a program that uses Prim's algorithm to find the minimum spanning tree (MST) of a weighted graph representing computers and cable costs.
📋 What You'll Learn
Create a graph as an adjacency matrix with exact weights
Create a variable to track visited nodes
Implement Prim's algorithm core logic to find MST
Print the edges in MST with their weights
💡 Why This Matters
🌍 Real World
Network design to minimize cable costs while connecting all computers.
💼 Career
Understanding MST algorithms is important for roles in network engineering, operations research, and software development involving graph problems.
Progress0 / 4 steps
1
Create the graph as an adjacency matrix
Create a variable called graph as a 2D array (number[][]) with these exact values representing the weighted connections between 5 computers: [[0, 2, 0, 6, 0], [2, 0, 3, 8, 5], [0, 3, 0, 0, 7], [6, 8, 0, 0, 9], [0, 5, 7, 9, 0]]
DSA Typescript
Hint
Use a 2D array with exact rows and columns for the graph weights.
2
Create a visited array to track included nodes
Create a boolean array called visited with 5 elements, all set to false, to track which computers are included in the MST.
DSA Typescript
Hint
Use an array of booleans with 5 false values.
3
Implement Prim's algorithm core logic
Write a function called primMST that: - Starts from node 0 and marks it visited - Repeats 4 times to add edges - Finds the minimum weight edge from visited to unvisited nodes - Marks the new node visited and stores the edge in mstEdges array as tuples [from, to, weight] Use variables minWeight, minEdge, and loops with visited and graph inside the function.
DSA Typescript
Hint
Use nested loops to find the smallest edge connecting visited to unvisited nodes and store edges in an array.
4
Print the edges in the MST
Call the primMST() function and print each edge in the returned array mstEdges in the format: "Edge from X to Y with weight Z".
DSA Typescript
Hint
Call primMST(), then print each edge with template strings.
Practice
(1/5)
1. What is the main goal of Prim's algorithm in graph theory?
easy
A. To find the minimum spanning tree connecting all vertices with the least total edge weight
B. To find the shortest path between two vertices
C. To detect cycles in a graph
D. To sort vertices based on their degree
Solution
Step 1: Understand Prim's algorithm purpose
Prim's algorithm builds a tree connecting all vertices with minimum total edge weight.
Step 2: Compare with other graph algorithms
Shortest path and cycle detection are different problems; Prim's focuses on spanning tree.
Final Answer:
To find the minimum spanning tree connecting all vertices with the least total edge weight -> Option A
Hint: Add chosen edge weights stepwise to get MST total [OK]
Common Mistakes:
Forgetting to add the first vertex key (0) to total
Adding all edges instead of MST edges
Mixing up vertex indices
4. The following TypeScript code for Prim's algorithm has a bug. What is the error?
function primMST(graph: number[][]): number {
const n = graph.length;
const key = new Array(n).fill(Infinity);
const mstSet = new Array(n).fill(false);
key[0] = 0;
let totalWeight = 0;
for (let count = 0; count <= n - 1; count++) {
let min = Infinity;
let u = -1;
for (let v = 0; v < n; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
u = v;
}
}
mstSet[u] = true;
totalWeight += min;
for (let v = 0; v < n; v++) {
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
key[v] = graph[u][v];
}
}
}
return totalWeight;
}
medium
A. The inner loop condition should be v <= n
B. The key array is not initialized correctly
C. The mstSet array should be initialized with true values
D. The outer loop runs one extra time causing an invalid vertex selection
Solution
Step 1: Analyze outer loop range
The loop runs from 0 to n inclusive (<= n - 1), which means n iterations instead of n-1.
Step 2: Understand impact of extra iteration
Extra iteration causes selection of u = -1 (no valid vertex), leading to errors or invalid updates.
Final Answer:
The outer loop runs one extra time causing an invalid vertex selection -> Option D
Quick Check:
Loop count must be n-1, not n [OK]
Hint: Outer loop should run n-1 times, not n [OK]
Common Mistakes:
Using <= instead of < in loop condition
Initializing mstSet incorrectly
Changing inner loop bounds wrongly
5. Given a weighted undirected graph represented by the adjacency matrix below, apply Prim's algorithm starting from vertex 0. Which edges are included in the MST?