NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Minimum Spanning Trees Prims and Kruskal algorithm

A Minimum Spanning Tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all vertices together, without any cycles, and with the minimum possible total edge weight.


Theory & Explanation

Minimum Spanning Trees (MST): Prim's and Kruskal's Algorithms

1. Definition and Key Concepts

A Spanning Tree of a connected, undirected graph G = (V, E) is a subgraph that is a tree and includes all of the vertices of G. In other words, a spanning tree connects all vertices in a graph without forming any cycles. A graph can have multiple spanning trees.

A Minimum Spanning Tree (MST) or minimum weight spanning tree is a spanning tree whose weight (the sum of the weights of its edges) is less than or equal to the weight of every other spanning tree. The weight of an MST is the minimum possible for any tree that connects all vertices.

  • Graph type: The graph must be connected and weighted. (If the graph is not connected, we look for a Minimum Spanning Forest).
  • Cycles: An MST must be acyclic.
  • Number of edges: If a graph has V vertices, every spanning tree (and thus every MST) must have exactly V - 1 edges.
  • Uniqueness: If all edge weights in a graph are distinct, the MST is unique. Otherwise, there might be multiple spanning trees with the same minimum weight.

2. Graphical Representation of MST Construction

We will use a simple weighted graph to illustrate both Prim's and Kruskal's algorithms. The goal is to connect all nodes (A, B, C, D) with the minimum total weight.

Sample Weighted Graph

A B C D 1 2 3 4 5 6

Nodes {A, B, C, D}, Edges {(A,C,1), (A,D,2), (C,D,3), (B,A,4), (B,D,5), (B,C,6)}. Dashed edge (6) is redundant.

Resulting MST (Prim's/Kruskal's)

A B C D

Edges: (A,C,1), (A,D,2), (B,A,4)
Total Weight: 1 + 2 + 4 = 7

3. Prim's Algorithm

Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. It builds the tree one vertex at a time, starting from an arbitrary vertex. At each step, it adds the minimum weight edge that connects a vertex in the tree to a vertex outside the tree.

Algorithm Steps

  1. Initialize a tree with a single vertex, chosen arbitrarily from the graph.
  2. Maintain a set of visited vertices (those already in the MST) and unvisited vertices.
  3. While the set of unvisited vertices is not empty:
    • Find the minimum weight edge that connects a visited vertex to an unvisited vertex.
    • Add this edge to the MST and mark the corresponding unvisited vertex as visited.

Example Walkthrough (Starting from A on graph above)

  • 1. Start with visited set: {A}. Available edges from A: (A,C,1), (A,D,2), (B,A,4). Min weight is 1.
  • 2. Add edge (A,C,1). Visited set: {A, C}. Available edges from A or C: (A,D,2), (B,A,4), (C,D,3), (B,C,6). Min weight is 2.
  • 3. Add edge (A,D,2). Visited set: {A, C, D}. Available edges from A, C, or D: (B,A,4), (C,D,3), (B,D,5), (B,C,6). Min weight is 3 (already connected to C) or 4 (leads to unvisited B). Select 4.
  • 4. Add edge (B,A,4). Visited set: {A, C, D, B}. All vertices are visited.

Prim's Result Edges: (A,C,1), (A,D,2), (B,A,4) - Total = 7

4. Kruskal's Algorithm

Kruskal's algorithm is also a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. It sorts all edges in the graph in non-decreasing order of their weight and adds edges to the MST one by one, provided that the edge does not form a cycle with the edges already in the MST.

Algorithm Steps

  1. Sort all the edges in the graph in non-decreasing order of their weight.
  2. Iterate through the sorted edges:
    • For each edge, check if adding it to the current MST forms a cycle.
    • If no cycle is formed, add the edge to the MST.
    • If a cycle is formed, discard the edge.
  3. Repeat step 2 until the MST contains exactly V - 1 edges.

Note: To efficiently detect cycles, Kruskal's algorithm typically uses the Disjoint-Set Union (DSU) data structure.

Example Walkthrough (Using edges from graph above)

  • 1. Sort edges by weight: (A,C,1), (A,D,2), (C,D,3), (B,A,4), (B,D,5), (B,C,6).
  • 2. Add (A,C,1): MST = {(A,C)}.
  • 3. Add (A,D,2): No cycle. MST = {(A,C), (A,D)}.
  • 4. Add (C,D,3): Cycle formed (A-C-D-A). Discard.
  • 5. Add (B,A,4): No cycle. MST = {(A,C), (A,D), (B,A)}.
  • 6. MST has V-1 = 3` edges. Stop.

Kruskal's Result Edges: (A,C,1), (A,D,2), (B,A,4) - Total = 7

5. Time Complexity Analysis

Algorithm Data Structure Time Complexity
Prim's Adjacency Matrix + Min-Heap (for edge weights) O(E log V)
Prim's Adjacency List + Fibonacci Heap (advanced) O(E + V log V)
Kruskal's Sorting edges + Disjoint-Set Union (DSU) O(E log E + E log V) or O(E log E)

6. C Program: Prim's Algorithm

Note: This implementation uses an adjacency matrix and a simple approach to find the minimum edge weight for O(V^2) complexity, which is suitable for student exams on smaller graphs.

#include <stdio.h>
#include <limits.h>

#define V 4 // Number of vertices

// Function to find the vertex with minimum key value, 
// from the set of vertices not yet included in MST
int minKey(int key[], int mstSet[]) {
    int min = INT_MAX, min_index;

    for (int v = 0; v < V; v++)
        if (mstSet[v] == 0 && key[v] < min)
            min = key[v], min_index = v;

    return min_index;
}

// Function to print the constructed MST stored in parent[]
void printMST(int parent[], int graph[V][V]) {
    printf("Edge \tWeight\n");
    int totalWeight = 0;
    for (int i = 1; i < V; i++) {
        printf("%c - %c \t%d \n", parent[i] + 'A', i + 'A', graph[i][parent[i]]);
        totalWeight += graph[i][parent[i]];
    }
    printf("Total Weight of MST: %d\n", totalWeight);
}

// Function to construct and print MST for a graph represented
// using adjacency matrix representation
void primMST(int graph[V][V]) {
    int parent[V]; // Array to store constructed MST
    int key[V];    // Key values used to pick minimum weight edge in cut
    int mstSet[V]; // To represent set of vertices not yet included in MST

    // Initialize all keys as INFINITE and mstSet[] as 0
    for (int i = 0; i < V; i++) {
        key[i] = INT_MAX;
        mstSet[i] = 0;
    }

    // Always include first vertex in MST.
    key[0] = 0;     // Make key 0 so that this vertex is picked first.
    parent[0] = -1; // First node is always root of MST

    // The MST will have V vertices
    for (int count = 0; count < V - 1; count++) {
        // Pick the minimum key vertex from the set of vertices
        // not yet included in MST
        int u = minKey(key, mstSet);

        // Add the picked vertex to the mstSet
        mstSet[u] = 1;

        // Update key value and parent index of the adjacent vertices
        // of the picked vertex. Consider only those vertices which are not
        // yet included in MST
        for (int v = 0; v < V; v++)
            // graph[u][v] is non-zero only for adjacent vertices of u
            // mstSet[v] is false for vertices not yet included in MST
            // Update the key only if graph[u][v] is smaller than key[v]
            if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
                parent[v] = u;
                key[v] = graph[u][v];
            }
    }

    // print the constructed MST
    printMST(parent, graph);
}

int main() {
    // Representing the graph from Fig 1 using Adjacency Matrix
    // Vertices: 0=A, 1=B, 2=C, 3=D
    int graph[V][V] = { 
        { 0, 4, 1, 2 }, // A connects to B(4), C(1), D(2)
        { 4, 0, 6, 5 }, // B connects to A(4), C(6), D(5)
        { 1, 6, 0, 3 }, // C connects to A(1), B(6), D(3)
        { 2, 5, 3, 0 }  // D connects to A(2), B(5), C(3)
    };

    printf("Prim's Algorithm MST Construction:\n");
    primMST(graph);

    return 0;
}

Expected Output (C):

Prim's Algorithm MST Construction:
Edge 	Weight
A - C 	1 
A - D 	2 
A - B 	4 
Total Weight of MST: 7

(Note: The output represents the same MST: Edges A-C, A-D, and B-A with weights 1, 2, and 4 respectively.)

7. Python Program: Kruskal's Algorithm

Note: This implementation uses an adjacency list representation of edges and a Disjoint-Set Union (DSU) data structure for efficient cycle detection, which is essential for Kruskal's.

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

    def find(self, i):
        if self.parent[i] == i:
            return i
        # Path compression
        self.parent[i] = self.find(self.parent[i])
        return self.parent[i]

    def union(self, i, j):
        root_i = self.find(i)
        root_j = self.find(j)
        if root_i != root_j:
            # Union by rank
            if self.rank[root_i] < self.rank[root_j]:
                self.parent[root_i] = root_j
            elif self.rank[root_i] > self.rank[root_j]:
                self.parent[root_j] = root_i
            else:
                self.parent[root_i] = root_j
                self.rank[root_j] += 1
            return True
        return False

class Graph:
    def __init__(self, vertices):
        self.V = vertices
        self.graph = []

    def add_edge(self, u, v, w):
        self.graph.append([u, v, w])

    def kruskal_mst(self):
        mst = []
        # 1. Sort all edges in non-decreasing order of their weight
        self.graph = sorted(self.graph, key=lambda item: item[2])
        
        dsu = DSU(self.V)
        
        mst_weight = 0
        edge_count = 0
        
        # 2. Iterate through sorted edges
        for u, v, w in self.graph:
            # Check if adding this edge forms a cycle
            if dsu.union(u, v):
                mst.append((u, v, w))
                mst_weight += w
                edge_count += 1
                
            # If MST has V-1 edges, stop
            if edge_count == self.V - 1:
                break
                
        return mst, mst_weight

if __name__ == "__main__":
    # Representing the graph from Fig 1 using Adjacency List
    # Vertices: 0=A, 1=B, 2=C, 3=D
    g = Graph(4)
    g.add_edge(0, 1, 4) # A-B (4)
    g.add_edge(0, 2, 1) # A-C (1)
    g.add_edge(0, 3, 2) # A-D (2)
    g.add_edge(1, 2, 6) # B-C (6)
    g.add_edge(1, 3, 5) # B-D (5)
    g.add_edge(2, 3, 3) # C-D (3)

    print("Kruskal's Algorithm MST Construction:")
    mst_edges, total_weight = g.kruskal_mst()
    
    print("Edge \tWeight")
    for u, v, w in mst_edges:
        print(f"{chr(u + ord('A'))} - {chr(v + ord('A'))} \t{w}")
    print(f"Total Weight of MST: {total_weight}")

Expected Output (Python):

Kruskal's Algorithm MST Construction:
Edge 	Weight
A - C 	1
A - D 	2
A - B 	4
Total Weight of MST: 7

(Note: Again, the output correctly identifies the same minimum set of edges.)

Diagrams

minimum-spanning-trees-prims-and-kruskal-algorithm - Diagram

minimum-spanning-trees-prims-and-kruskal-algorithm - Diagram

minimum-spanning-trees-prims-and-kruskal-algorithm - Diagram

minimum-spanning-trees-prims-and-kruskal-algorithm - Diagram

Advertisement
Advertisement