📖 Scenario: You are working as a network engineer. You have a list of cities connected by roads with different costs. Your goal is to connect all cities with the minimum total road cost, so the network is efficient and cost-effective.
🎯 Goal: Build a program that uses Kruskal's algorithm to find the minimum spanning tree (MST) of a graph represented by edges with costs. The MST connects all cities with the least total cost.
📋 What You'll Learn
Create a list of edges with city pairs and their costs
Create a helper structure to track connected components (disjoint sets)
Implement Kruskal's algorithm to select edges for MST
Print the edges included in the MST and the total cost
💡 Why This Matters
🌍 Real World
Network design, such as connecting cities with roads or computers with cables at minimum cost.
💼 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 list of edges
Create a list called edges of tuples with these exact entries: ("A", "B", 4), ("A", "C", 3), ("B", "C", 1), ("B", "D", 2), ("C", "D", 4), ("D", "E", 2), ("E", "F", 6)
DSA C#
Hint
Use List<(string, string, int)> and add the exact tuples inside curly braces.
2
Create the Disjoint Set helper
Create a class called DisjointSet with methods Find and Union to track connected components. Inside Main, create a DisjointSet instance called ds and initialize it with the unique cities A, B, C, D, E, F.
DSA C#
Hint
Use a dictionary to store parents. Initialize each city as its own parent. Implement Find with path compression and Union to merge sets.
3
Implement Kruskal's algorithm
Sort the edges list by cost ascending. Create a list called mst to store edges in the minimum spanning tree. Use a for loop with variables city1, city2, cost to iterate over edges. For each edge, if ds.Find(city1) is not equal to ds.Find(city2), add the edge to mst and call ds.Union(city1, city2).
DSA C#
Hint
Sort edges by cost. Loop over edges with foreach (var (city1, city2, cost) in edges). Use Find to check if cities are in different sets. If yes, add edge to MST and union sets.
4
Print the MST edges and total cost
Create a variable totalCost initialized to 0. Use a foreach loop with variables city1, city2, cost to iterate over mst. Inside the loop, print the edge in the format "city1 - city2: cost" and add cost to totalCost. After the loop, print "Total cost: totalCost".
DSA C#
Hint
Use a variable totalCost to sum costs. Print each edge in MST with Console.WriteLine. Finally, print total cost.
Practice
(1/5)
1. What is the main goal of Kruskal's Algorithm in graph theory?
easy
A. To sort the vertices of a graph
B. To find the shortest path between two nodes
C. To find the minimum spanning tree of a connected weighted graph
D. To detect cycles in a graph
Solution
Step 1: Understand the purpose of Kruskal's Algorithm
Kruskal's Algorithm is designed to find a subset of edges that connects all vertices with the minimum total edge weight and no cycles.
Step 2: Compare with other graph algorithms
Unlike shortest path algorithms or cycle detection, Kruskal's focuses on building a minimum spanning tree.
Final Answer:
To find the minimum spanning tree of a connected weighted graph -> Option C
Quick Check:
Minimum Spanning Tree = To find the minimum spanning tree of a connected weighted graph [OK]
Hint: Kruskal connects all nodes with least total edge weight [OK]
Common Mistakes:
Confusing MST with shortest path
Thinking Kruskal detects cycles only
Assuming it sorts vertices
2. Which of the following C# code snippets correctly initializes a list of edges for Kruskal's Algorithm?
easy
A. var edges = new List<(int, int, int)> { (0, 1, 4), (1, 2, 3) };
B. var edges = new List { [0, 1, 4], [1, 2, 3] };
C. var edges = new List<(int, int, int)> { [0, 1, 4], [1, 2, 3] };
D. var edges = new List<(int, int)> { (0, 1), (1, 2) };
Solution
Step 1: Check tuple syntax for edges
In C#, tuples are declared with parentheses and commas, e.g., (int, int, int). var edges = new List<(int, int, int)> { (0, 1, 4), (1, 2, 3) }; uses this correctly.
Step 2: Identify incorrect list initializations
var edges = new List { [0, 1, 4], [1, 2, 3] }; uses square brackets inside List initialization which is invalid. var edges = new List<(int, int, int)> { [0, 1, 4], [1, 2, 3] }; mixes tuple and array syntax incorrectly. var edges = new List<(int, int)> { (0, 1), (1, 2) }; misses the weight part of edges.
Final Answer:
var edges = new List<(int, int, int)> { (0, 1, 4), (1, 2, 3) }; -> Option A
Quick Check:
Correct tuple list syntax = var edges = new List<(int, int, int)> { (0, 1, 4), (1, 2, 3) }; [OK]
Hint: Use parentheses for tuples, curly braces for list initialization [OK]
Common Mistakes:
Using square brackets for tuples
Omitting edge weights
Mixing array and tuple syntax
3. What is the output MST edges after running Kruskal's Algorithm on this graph?
Pick (0-1:1), then (1-2:2). Adding (0-2:3) creates a cycle, so skip. Add (2-3:4).
Final Answer:
[(0,1,1), (1,2,2), (2,3,4)] -> Option B
Quick Check:
Edges chosen without cycle = [(0,1,1), (1,2,2), (2,3,4)] [OK]
Hint: Sort edges by weight, skip edges forming cycles [OK]
Common Mistakes:
Including edges that form cycles
Not sorting edges by weight
Missing edges to connect all vertices
4. Identify the error in this Kruskal's Algorithm snippet:
var edges = new List<(int, int, int)> { (0,1,1), (1,2,2), (0,2,3) };
var parent = new int[3];
for(int i=0; i<3; i++) parent[i] = i;
int Find(int x) {
if(parent[x] == x) return x;
return Find(parent[x]);
}
void Union(int a, int b) {
int rootA = Find(a);
int rootB = Find(b);
parent[rootA] = rootB;
}
foreach(var edge in edges) {
int u = edge.Item1, v = edge.Item2;
if(Find(u) != Find(v)) {
Union(u, v);
Console.WriteLine($"Edge: {u}-{v}");
}
}
medium
A. Union function does not use union by rank or size, causing inefficiency
B. Find function lacks path compression, causing stack overflow
C. Parent array size is incorrect for the number of vertices
D. Edges list is missing weights, so MST cannot be formed
Solution
Step 1: Check parent array size
There are 3 vertices (0,1,2), so parent array size 3 is correct for these vertices.
Step 2: Verify if all vertices are covered
Edges use vertices 0,1,2 only, so parent array size matches vertices count. No error here.
Step 3: Eliminate incorrect options
Parent array size [3] is correct for vertices 0-2 (C wrong). Edges include weights (D wrong). Path compression absent but no stack overflow for small graph (B wrong). Thus, A is correct: lacking union by rank or size causes inefficiency.
Final Answer:
Union function does not use union by rank or size, causing inefficiency -> Option A
Quick Check:
Missing union by rank causes inefficiency = Union function does not use union by rank or size, causing inefficiency [OK]
Hint: Check array sizes and union-find optimizations carefully [OK]
Common Mistakes:
Confusing inefficiency with error
Assuming missing weights when present
Ignoring union-find optimization importance
5. Given a graph with vertices 0 to 4 and edges:
var edges = new List<(int, int, int)> {
(0,1,10), (0,2,6), (0,3,5), (1,3,15), (2,3,4), (3,4,2)
};
Apply Kruskal's Algorithm to find the total weight of the minimum spanning tree.