# Calculate the Minimum Spanning Tree of a Graph (Solved)

## Introduction to the Minimum Spanning Tree

A Minimum Spanning Tree (MST) is a tree that spans all the vertices in a connected, undirected graph and has the minimum possible total edge weight. In other words, it is a tree that connects all the nodes in a graph such that the total weight of the edges is minimized.

Minimum Spanning Trees are used in various real-world scenarios, such as designing an efficient computer network, road networks, and electrical wiring.

## Real-World Examples and Scenarios

Designing an efficient computer network: In a computer network, each computer is connected to other computers through network cables. To connect all computers with the minimum length of cables, an MST can be used to find the optimal connections.

Road networks: When designing road networks, the goal is to connect all cities with the minimum total length of roads. An MST can help find the optimal way to connect all the cities.

Electrical wiring: In electrical wiring systems, the goal is to connect all electrical components with minimal wire length to reduce costs. An MST can be used to find the optimal way to connect all components.

## Real-World Scenario: Planning a Fiber Optic Network

Consider a telecommunications company that wants to expand its fiber-optic network to a new region with several cities. The company wants to connect all the cities with the minimum length of fiber-optic cables. This problem can be represented as a graph with cities as nodes and the distance between cities as edge weights.

The problem can be formally defined as follows:

Given: A connected, undirected graph G = (V, E) with non-negative edge weights w(u, v) for each edge (u, v) in E.

Objective: Find a tree T = (V, E') such that the sum of edge weights in T is minimized, and T is a spanning tree of G.

To find the Minimum Spanning Tree of this graph, we can use algorithms such as Kruskal's Algorithm or Prim's Algorithm. In this lesson, we will explore Kruskal's Algorithm.

## Kruskal's Algorithm

Kruskal's Algorithm is a greedy algorithm that works by sorting all the edges in the graph in non-decreasing order of their weights, and then iteratively adding the edges to the MST, as long as they do not form a cycle.

The algorithm is as follows:

1. Sort all the edges in the graph in non-decreasing order of their weights.
2. Initialize an empty set T to store the edges of the MST.
3. For each edge (u, v) in the sorted list of edges: a. If adding (u, v) to T does not form a cycle, add (u, v) to T.
4. Return T.

To determine whether adding an edge to the MST forms a cycle, we can use the Union-Find data structure.

## Union-Find Data Structure

The Union-Find data structure is used to efficiently determine whether adding an edge forms a cycle in the MST. It consists of two operations:

1. Find: Determine the set to which an element belongs.
2. Union: Merge two sets into one.

Initially, each vertex is in its own set. When we add an edge (u, v) to the MST, we merge the sets of u and v. If u and v are already in the same set, adding the edge (u, v) will create a cycle.

## Implementing Kruskal's Algorithm

Let's implement Kruskal's Algorithm to find the Minimum Spanning Tree of the fiber-optic network graph.

### Step 1: Sort the Edges

First, we need to sort the edges of the graph in non-decreasing order of their weights. We can represent the graph as a list of edges, where each edge is a tuple (u, v, w), with u and v being the vertices, and w being the weight of the edge.

``````def sort_edges(graph):
return sorted(graph, key=lambda edge: edge[2])
``````

### Step 2: Initialize the MST Set

Next, we initialize an empty set T to store the edges of the MST.

``````def init_mst_set():
return set()
``````

### Step 3: Add Edges to the MST

Now, we iterate through the sorted list of edges and add each edge to the MST if it does not form a cycle. To do this, we need to implement the Union-Find data structure.

``````class UnionFind:
def __init__(self, vertices):
self.parent = {v: v for v in vertices}
self.rank = {v: 0 for v in vertices}

def find(self, vertex):
if self.parent[vertex] != vertex:
self.parent[vertex] = self.find(self.parent[vertex])
return self.parent[vertex]

def union(self, u, v):
root_u = self.find(u)
root_v = self.find(v)

if root_u == root_v:
return False

if self.rank[root_u] > self.rank[root_v]:
self.parent[root_v] = root_u
elif self.rank[root_u] < self.rank[root_v]:
self.parent[root_u] = root_v
else:
self.parent[root_v] = root_u
self.rank[root_u] += 1

return True
``````

With the Union-Find data structure implemented, we can now add edges to the MST.

``````def kruskal(graph, vertices):
sorted_edges = sort_edges(graph)
mst_set = init_mst_set()
uf = UnionFind(vertices)

for edge in sorted_edges:
u, v, w = edge
if uf.union(u, v):

return mst_set
``````

### Example: Applying Kruskal's Algorithm

Let's apply Kruskal's Algorithm to our fiber-optic network graph.

``````graph = [
('A', 'B', 5),
('A', 'C', 10),
('B', 'C', 7),
('B', 'D', 6),
('C', 'E', 12),
('D', 'E', 8),
('D', 'F', 14),
('E', 'F', 4),
]

vertices = {'A', 'B', 'C', 'D', 'E', 'F'}

mst = kruskal(graph, vertices)
print(mst)
``````

The output of the program will be:

``````{('A', 'B', 5), ('B', 'D', 6), ('E', 'F', 4), ('B', 'C', 7), ('D', 'E', 8)}
``````

This is the Minimum Spanning Tree of the fiber-optic network graph.

## Conclusion

In this lesson, we have explained what a Minimum Spanning Tree is and explored real-world examples and scenarios where it is used. We have demonstrated how to use Kruskal's Algorithm to find the Minimum Spanning Tree of a graph and provided actual code examples.

The solution provided in this lesson can be applied to other real-world problems with similar requirements, such as designing road networks, electrical wiring systems, and computer networks.

## Learn to code in our 100% online programs

Altcademy coding bootcamp offers beginner-friendly, online programs designed by industry experts to help you become a coder. 85%+ of Altcademy alumni are hired within 6 months after graduation. See how we teach, or click on one of the following programs to find out more.