Prim’s and Kruskal’s Algorithm

                                                   

  Prim's Algorithm




                                              



Prim's algorithm, named after its developer Robert C. Prim, is a widely used algorithm in graph theory and computer science for finding the minimum spanning tree (MST) of a connected, undirected graph. A minimum spanning tree is a subset of the graph's edges that forms a tree (a connected acyclic graph) and spans all the vertices in the original graph while minimizing the total edge weight. The primary application of minimum spanning trees is in network design, such as designing efficient transportation or communication networks.

Here's an overview of how Prim's algorithm works:

1. Initialize an empty set (or priority queue) to represent the minimum spanning tree.
2. Start with an arbitrary vertex as the initial MST. You can choose any vertex from the graph.
3. Find the minimum-weight edge that connects a vertex in the MST to a vertex outside the MST.
4. Add this edge to the MST.
5. Repeat steps 3 and 4 until the MST spans all the vertices in the original graph (i.e., the MST has V-1 edges, where V is the number of vertices in the graph).

The algorithm maintains two sets of vertices: one in the MST and one outside. It repeatedly grows the MST by selecting the minimum-weight edge that connects a vertex in the MST to a vertex outside the MST. This process continues until all vertices are included in the MST.

Prim's algorithm ensures that the resulting minimum spanning tree has the minimum possible total edge weight. It is efficient and straightforward to implement, making it a popular choice for solving minimum spanning tree problems in practice. The data structure used to efficiently find the minimum-weight edge can vary, with options like priority queues or Fibonacci heaps for optimizing the algorithm's performance.



Let's walk through an example of Prim's algorithm to find the minimum spanning tree (MST) of a graph. In this example, we'll use a simple graph with the following vertices and edge weights:

Vertices: A, B, C, D, E, F

Edges and Weights:
- AB: 5
- AC: 2
- BD: 4
- BE: 2
- CF: 3
- CD: 1
- DE: 7

We will start the algorithm with vertex A as the initial MST and find the edges that progressively grow the tree. The numbers next to the vertices represent their weights in the MST.

1. Start with A as the initial MST:
   MST: A
   Total Weight: 0

2. Find the minimum-weight edge connecting A (in MST) to an outside vertex:
   - AC: 2
   Add AC to the MST.
   MST: A --2-- C
   Total Weight: 2

3. Find the minimum-weight edge connecting vertices in the MST to an outside vertex:
   - CD: 1
   Add CD to the MST.
   MST: A --2-- C --1-- D
   Total Weight: 3

4. Find the minimum-weight edge connecting vertices in the MST to an outside vertex:
   - CF: 3
   Add CF to the MST.
   MST: A --2-- C --1-- D
              |
              3
              |
              F
   Total Weight: 6

5. Find the minimum-weight edge connecting vertices in the MST to an outside vertex:
   - BE: 2
   Add BE to the MST.
   MST: A --2-- C --1-- D
              |      |
              3      2
              |      |
              F --2-- E
   Total Weight: 8

6. Find the minimum-weight edge connecting vertices in the MST to an outside vertex:
   - BD: 4
   Add BD to the MST.
   MST: A --2-- C --1-- D
              |      |
              3      2
              |      |
              F --2-- E
                   |
                   4
                   |
                   B
   Total Weight: 12

At this point, all vertices are included in the MST, and the MST is complete. The total weight of the minimum spanning tree is 12, and the edges forming the MST are:

- AC (weight 2)
- CD (weight 1)
- CF (weight 3)
- BE (weight 2)
- BD (weight 4)

These edges together form the minimum spanning tree for the given graph.




Here's a simple implementation of Prim's algorithm in C for finding the minimum spanning tree of a graph. In this example, I'll use an adjacency matrix to represent the graph. You can adapt it for your specific graph representation.

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

#define V 6 // Number of vertices in the graph

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;
}

void printMST(int parent[], int graph[V][V]) {
    printf("Edge \tWeight\n");
    for (int i = 1; i < V; i++) {
        printf("%d - %d \t%d\n", parent[i], i, graph[i][parent[i]]);
    }
}

void primMST(int graph[V][V]) {
    int parent[V];
    int key[V];
    int mstSet[V];
    
    for (int i = 0; i < V; i++) {
        key[i] = INT_MAX;
        mstSet[i] = 0;
    }
    
    key[0] = 0;
    parent[0] = -1;
    
    for (int count = 0; count < V - 1; count++) {
        int u = minKey(key, mstSet);
        mstSet[u] = 1;
        
        for (int v = 0; v < V; v++) {
            if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
                parent[v] = u;
                key[v] = graph[u][v];
            }
        }
    }
    
    printMST(parent, graph);
}

int main() {
    int graph[V][V] = {
        {0, 5, 2, 0, 0, 0},
        {5, 0, 0, 4, 2, 0},
        {2, 0, 0, 1, 0, 3},
        {0, 4, 1, 0, 7, 0},
        {0, 2, 0, 7, 0, 0},
        {0, 0, 3, 0, 0, 0}
    };
    
    primMST(graph);
    
    return 0;
}
```

This code defines `primMST` to find the minimum spanning tree for the provided graph and `printMST` to print the resulting minimum spanning tree. Adjust the values in the `graph` array and the number of vertices `V` to fit your specific graph. This example assumes an adjacency matrix representation.















            Kruskal's Algorithm






                                      




Kruskal's algorithm is another popular algorithm for finding the minimum spanning tree (MST) of a connected, undirected graph. Like Prim's algorithm, Kruskal's algorithm is used to find a subset of edges in the graph that forms a tree, spanning all the vertices while minimizing the total edge weight. The key difference is in the way the algorithm works.

Here's an overview of how Kruskal's algorithm works:

1. Start with an empty set of edges, which will eventually form the MST.
2. Sort all the edges in the graph by their weights in non-decreasing order.
3. Iterate through the sorted edges, adding them to the MST if adding the edge does not create a cycle in the MST. To check for cycles, you can use a disjoint-set data structure (union-find data structure).
4. Continue this process until the MST has V-1 edges, where V is the number of vertices in the graph.

Kruskal's algorithm ensures that the resulting minimum spanning tree has the minimum possible total edge weight, just like Prim's algorithm. It is efficient and relatively easy to implement, making it a popular choice for solving minimum spanning tree problems in practice. Kruskal's algorithm has a different approach in that it focuses on sorting and selecting edges based on their weights, rather than starting from a single vertex as in Prim's algorithm.

The algorithm is named after Joseph Kruskal, who first described it in 1956.





Let's walk through an example of Kruskal's algorithm to find the minimum spanning tree (MST) of a graph. In this example, we'll use a simple graph with the following vertices and edge weights:

Vertices: A, B, C, D, E, F

Edges and Weights:
- AB: 5
- AC: 2
- BD: 4
- BE: 2
- CF: 3
- CD: 1
- DE: 7

We will start the algorithm with an empty set and progressively add edges to construct the MST. The numbers next to the vertices represent their set representatives in a disjoint-set data structure (initially each vertex is in its own set).

1. Sort the edges by their weights in non-decreasing order:

   - CD: 1
   - BE: 2
   - AC: 2
   - CF: 3
   - BD: 4
   - AB: 5
   - DE: 7

2. Start with an empty set and iterate through the sorted edges:

   - CD: 1 (Add CD to MST, merging sets C and D)
     - A, B
     - C, D
     - E
     - F

   - BE: 2 (Add BE to MST, merging sets B and E)
     - A
     - C, D
     - B, E
     - F

   - AC: 2 (Add AC to MST, merging sets A and C)
     - A, C, D, B, E
     - F

   - CF: 3 (Add CF to MST, merging sets C and F)
     - A, C, D, B, E
     - C, F

   - BD: 4 (Add BD to MST, merging sets B and D)
     - A, C, D, B, E
     - C, F
     - A, C, D, B, E

   - AB: 5 (Add AB to MST, merging sets A and B)
     - A, C, D, B, E
     - C, F
     - A, C, D, B, E

   - DE: 7 (Add DE to MST, merging sets D and E)
     - A, C, D, B, E
     - C, F
     - A, C, D, B, E
     - A, C, D, B, E

At this point, all vertices are part of a single set, and the MST is complete. The total weight of the minimum spanning tree is 1 + 2 + 2 + 3 + 4 + 5 = 17, and the edges forming the MST are:

- CD (weight 1)
- BE (weight 2)
- AC (weight 2)

- CF (weight 3)
- BD (weight 4)
- AB (weight 5)

These edges together form the minimum spanning tree for the given graph.








here's a simple implementation of Kruskal's algorithm in C to find the minimum spanning tree (MST) for the graph with the examples you provided. This code uses a disjoint-set (union-find) data structure to keep track of connected components:

```c
#include <stdio.h>
#include <stdlib.h>

// Define the structure for an edge
struct Edge {
    int src, dest, weight;
};

// Define the structure for a subset
struct Subset {
    int parent;
    int rank;
};

// Function to compare edges by weight (used for sorting)
int compareEdges(const void* a, const void* b) {
    return ((struct Edge*)a)->weight - ((struct Edge*)b)->weight;
}

// Find the representative of a set (uses path compression)
int find(struct Subset subsets[], int i) {
    if (subsets[i].parent != i)
        subsets[i].parent = find(subsets, subsets[i].parent);
    return subsets[i].parent;
}

// Union two sets by rank
void unionSets(struct Subset subsets[], int x, int y) {
    int rootX = find(subsets, x);
    int rootY = find(subsets, y);

    if (subsets[rootX].rank < subsets[rootY].rank)
        subsets[rootX].parent = rootY;
    else if (subsets[rootX].rank > subsets[rootY].rank)
        subsets[rootY].parent = rootX;
    else {
        subsets[rootY].parent = rootX;
        subsets[rootX].rank++;
    }
}

// Kruskal's algorithm to find the MST
void kruskalMST(struct Edge edges[], int V, int E) {
    struct Edge result[V]; // To store the MST
    int e = 0; // Index for the sorted edges
    int i = 0; // Index for the resulting MST

    // Sort the edges by weight
    qsort(edges, E, sizeof(edges[0]), compareEdges);

    // Allocate memory for subsets
    struct Subset subsets[V];
    for (int v = 0; v < V; v++) {
        subsets[v].parent = v;
        subsets[v].rank = 0;
    }

    // Keep adding edges to the MST until it has V-1 edges
    while (i < V - 1 && e < E) {
        struct Edge nextEdge = edges[e++];

        int x = find(subsets, nextEdge.src);
        int y = find(subsets, nextEdge.dest);

        if (x != y) {
            result[i++] = nextEdge;
            unionSets(subsets, x, y);
        }
    }

    // Print the MST
    printf("Edges in the Minimum Spanning Tree:\n");
    for (int i = 0; i < V - 1; i++) {
        printf("Edge %d-%d, Weight: %d\n", result[i].src, result[i].dest, result[i].weight);
    }
}

int main() {
    int V = 6; // Number of vertices
    int E = 7; // Number of edges

    // Define the edges and their weights
    struct Edge edges[] = {
        {0, 2, 2},
        {1, 3, 4},
        {2, 4, 2},
        {3, 5, 3},
        {2, 3, 1},
        {0, 1, 5},
        {4, 5, 7},
    };

    kruskalMST(edges, V, E);

    return 0;
}
```

You can adjust the number of vertices, edges, and the edge weights to match the graph you want to find the MST for. This code sorts the edges, applies Kruskal's algorithm, and prints the resulting MST.




Post a Comment

0 Comments