Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views1 page

Prims Algorithm Code

This C++ program implements Prim's algorithm to find the Minimum Spanning Tree (MST) of a graph represented by an adjacency matrix. The user inputs the number of vertices and the adjacency matrix, and the program outputs the edges included in the MST along with their weights. Finally, it displays the total weight of the MST.

Uploaded by

hemant7125pkxd
Copyright
© © All Rights Reserved
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% found this document useful (0 votes)
9 views1 page

Prims Algorithm Code

This C++ program implements Prim's algorithm to find the Minimum Spanning Tree (MST) of a graph represented by an adjacency matrix. The user inputs the number of vertices and the adjacency matrix, and the program outputs the edges included in the MST along with their weights. Finally, it displays the total weight of the MST.

Uploaded by

hemant7125pkxd
Copyright
© © All Rights Reserved
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
You are on page 1/ 1

#include <iostream>

using namespace std;

const int MAX = 10;


const int INF = 9999;

int main() {
int n, cost[MAX][MAX], selected[MAX] = {0};
int edges = 0, total = 0;

cout << "Enter number of vertices: ";


cin >> n;

cout << "Enter adjacency matrix (9999 for no connection):\n";


for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> cost[i][j];

selected[0] = 1;
cout << "\nEdges in MST:\nEdge\tWeight\n";

while (edges < n - 1) {


int min = INF, x = 0, y = 0;
for (int i = 0; i < n; i++) {
if (selected[i]) {
for (int j = 0; j < n; j++) {
if (!selected[j] && cost[i][j] < min) {
min = cost[i][j];
x = i;
y = j;
}
}
}
}
cout << x << " - " << y << "\t" << min << "\n";
total += min;
selected[y] = 1;
edges++;
}

cout << "Total Weight: " << total;


return 0;
}

You might also like