📖 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.This is a classic problem solved by finding a Minimum Spanning Tree (MST) in a network graph.
🎯 Goal: Build a program that uses Prim's Algorithm to find the Minimum Spanning Tree of a given weighted graph. The program will output the edges chosen and the total cost.
📋 What You'll Learn
Create a weighted graph using an adjacency matrix
Use a variable to track the number of vertices
Implement Prim's Algorithm to find the MST
Print the edges in the MST and the total cost
💡 Why This Matters
🌍 Real World
Network engineers use MST algorithms to design cost-effective networks connecting computers or routers.
💼 Career
Understanding MST and Prim's Algorithm is important for roles in network design, optimization, and software engineering involving graph problems.
Progress0 / 4 steps
1
Create the weighted graph using an adjacency matrix
Create a 2D integer array called graph with 5 vertices. Use this exact matrix:
Use a 2D array to represent the graph. Each row and column represents a vertex. The value is the cost between vertices. Zero means no direct connection.
2
Add a variable for the number of vertices
Create an integer variable called V and set it to 5 to represent the number of vertices in the graph.
DSA Java
Hint
This variable helps to control loops and array sizes.
3
Implement Prim's Algorithm core logic
Write a method called primMST that takes the graph and V as inputs. Inside, create arrays parent, key, and mstSet. Use a loop to pick the minimum key vertex not yet included in MST. Update keys and parents for adjacent vertices. Complete the MST construction logic.
DSA Java
Hint
Use arrays to track the MST structure and keys. Pick the smallest key vertex not in MST each time. Update neighbors' keys and parents.
4
Print the MST edges and total cost
Call the primMST method with graph and V as arguments. This will print the edges in the MST and the total cost.
DSA Java
Hint
Call the primMST method from main to see the MST edges and total cost printed.
Practice
(1/5)
1. What is the main goal of Prim's Algorithm in graph theory?
easy
A. To sort vertices based on their degree
B. To find the shortest path between two vertices
C. To detect cycles in a graph
D. To find the minimum spanning tree connecting all vertices with minimum total edge weight
Solution
Step 1: Understand Prim's Algorithm purpose
Prim's Algorithm builds a tree connecting all vertices with the smallest sum of edge weights.
Step 2: Compare with other graph tasks
It is not for shortest path, cycle detection, or sorting vertices.
Final Answer:
To find the minimum spanning tree connecting all vertices with minimum total edge weight -> Option D
2. Which of the following Java code snippets correctly initializes the key array for Prim's Algorithm for a graph with 5 vertices?
easy
A. int key[] = new int[5]; for(int i=0; i<5; i++) key[i] = 0;
B. int[] key = new int[5]; Arrays.fill(key, 0); key[0] = Integer.MAX_VALUE;
C. int[] key = new int[5]; Arrays.fill(key, Integer.MAX_VALUE); key[0] = 0;
D. int[] key = new int[5]; key[0] = Integer.MIN_VALUE; Arrays.fill(key, Integer.MAX_VALUE);
Solution
Step 1: Understand key array initialization
Key array stores minimum edge weights to vertices; initialize with max values except start vertex 0 with 0.
Step 2: Check each option
int[] key = new int[5]; Arrays.fill(key, Integer.MAX_VALUE); key[0] = 0; correctly sets all to Integer.MAX_VALUE and start vertex key[0] to 0.
Final Answer:
int[] key = new int[5]; Arrays.fill(key, Integer.MAX_VALUE); key[0] = 0; -> Option C
Quick Check:
Initialize keys with max except start = 0 [OK]
Hint: Start vertex key = 0, others = max value [OK]
Common Mistakes:
Setting all keys to 0
Setting start vertex key to max value
Incorrect order of fill and assignment
3. Given the following adjacency matrix for a graph with 4 vertices, what is the total weight of the minimum spanning tree found by Prim's Algorithm starting from vertex 0?
Step 1: Start from vertex 0 and pick minimum edges
Edges chosen: 0-1 (2), 1-2 (3), 0-3 (6)
Step 2: Sum the weights of chosen edges
Total weight = 2 + 3 + 6 = 11
Final Answer:
11 -> Option B
Quick Check:
Sum edges 2+3+6 = 11 [OK]
Hint: Add weights of edges chosen by Prim's stepwise [OK]
Common Mistakes:
Choosing wrong edges ignoring minimum weight
Adding edges that form cycles
Starting from wrong vertex
4. Identify the error in the following Java code snippet implementing Prim's Algorithm and select the correct fix:
int minKey(int[] key, boolean[] mstSet) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int v = 0; v < key.length; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
// Usage in main loop:
int u = minKey(key, mstSet);
mstSet[u] = true;
medium
A. No error; code correctly finds vertex with minimum key not in MST
B. minIndex should be initialized to 0 instead of -1
C. Return type should be void instead of int
D. The loop should start from 1 instead of 0
Solution
Step 1: Analyze minKey function logic
It finds vertex with smallest key not yet included in MST correctly.
Step 2: Check initialization and loop
minIndex = -1 is correct to detect no valid vertex; loop from 0 covers all vertices.
Final Answer:
No error; code correctly finds vertex with minimum key not in MST -> Option A
Quick Check:
minKey returns correct vertex index [OK]
Hint: minIndex = -1 signals no vertex found yet, loop from 0 covers all [OK]
Common Mistakes:
Changing minIndex initialization incorrectly
Changing return type wrongly
Starting loop from 1 misses vertex 0
5. You have a weighted undirected graph with 6 vertices and the following edges: