c语言邻接矩阵prim算法,C ++中的Prim算法(邻接矩阵表示的简单实现)

Prim的算法是一种贪婪的方法,用于为给定的加权无向图找到最小生成树。

加权图是所有边都有权重值的图。

无向图是一种特殊类型的图,其中所有边都是双向的。

最小生成树是一个子集,它包含所有边缘和顶点,但不包含循环,并且具有最小的总边缘权重。

在本文中,我们将学习prim的算法来找到最小生成树。通常,该算法使用两个数组,但是在此解决方案中,我们将仅使用一个。

该程序显示prim算法的实现。

示例#include 

using namespace std;

#define V 5

bool createsMST(int u, int v, vector inMST){

if (u == v)

return false;

if (inMST[u] == false && inMST[v] == false)

return false;

else if (inMST[u] == true && inMST[v] == true)

return false;

return true;

}

void printMinSpanningTree(int cost[][V]){

vector inMST(V, false);

inMST[0] = true;

int edgeNo = 0, MSTcost = 0;

while (edgeNo 

int min = INT_MAX, a = -1, b = -1;

for (int i = 0; i 

for (int j = 0; j 

if (cost[i][j] 

if (createsMST(i, j, inMST)) {

min = cost[i][j];

a = i;

b = j;

}

}

}

}

if (a != -1 && b != -1) {

cout<

MSTcost += min;

inMST[b] = inMST[a] = true;

}

}

cout<

}

int main() {

int cost[][V] = {

{ INT_MAX, 12, INT_MAX, 25, INT_MAX },

{ 12, INT_MAX, 11, 8, 12 },

{ INT_MAX, 11, INT_MAX, INT_MAX, 17 },

{ 25, 8, INT_MAX, INT_MAX, 15 },

{ INT_MAX, 12, 17, 15, INT_MAX },

};

cout<

printMinSpanningTree(cost);

return 0;

}

输出结果The Minimum spanning tree for the given tree is :

Edge 0 : (0 , 1 ) : cost = 12

Edge 1 : (1 , 3 ) : cost = 8

Edge 2 : (1 , 2 ) : cost = 11

Edge 3 : (1 , 4 ) : cost = 12

Cost of Minimum spanning tree =43

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值