The document contains a C program that implements Prim's algorithm to find the Minimum Spanning Tree (MST) of a graph represented by an adjacency matrix. It defines functions to find the minimum weight edge and to construct the MST, outputting the connections and weights of the vertices. The graph consists of four vertices, with specific weights between them defined in the adjacency matrix.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
2 views2 pages
15. Prims Algorithm
The document contains a C program that implements Prim's algorithm to find the Minimum Spanning Tree (MST) of a graph represented by an adjacency matrix. It defines functions to find the minimum weight edge and to construct the MST, outputting the connections and weights of the vertices. The graph consists of four vertices, with specific weights between them defined in the adjacency matrix.
// Function to find the vertex with the minimum weight
// among those not yet included in the MST int minRoad(int road[], bool mst[]) { int min = INT_MAX; int min_index = -1;
for (int i = 0; i < N; ++i) {
if (road[i] < min && !mst[i]) { min = road[i]; min_index = i; } } return min_index; }
// Prim's algorithm for building a Minimum Spanning Tree (MST)
void prim(int g[][N]) { int parent[N]; // Stores the parent of each vertex bool mst[N] = {false}; // Marks whether the vertex is included in the MST int road[N]; // Minimum distance to the MST
// Initialize all distances to infinity
for (int i = 0; i < N; ++i) road[i] = INT_MAX;
road[0] = 0; // Start from vertex 0
parent[0] = -1; // The root of the tree has no parent
for (int i = 0; i < N - 1; ++i) {
int index = minRoad(road, mst); // Select the vertex with the minimum edge mst[index] = true; // Include it in the MST