普里姆算法求最小生成树(MST-Prim algorithm)

最小生成树:带权图的生成树上的各边权 值之和称为这棵树的代价。最小代价生成 树是各边权值的总和最小的生成树。

普里姆算法(Prim)步骤:
1、选取源点作为最小生成树的结点,并初始化当前与生成树相连的最好情况,即权值最小的边

2、选取权值最小的边加入生成树,并更新各顶点的最好情况。

3、重复步骤2,直到所有顶点都加入生成树当中。

代码如下:
 
  
#include #include #include #define MAX 100 #define INF 10000000 typedef struct { int adjvex; //存放的这条权值最小的边的另一个顶点 int lowcost;           //存放的这条权值最小的边的权值 }Path; typedef struct { int arc[MAX][MAX]; int arcnum, vexnum; }AGraph; AGraph T; int minclosedge(Path closedge[]) { int min, j, k; min = INF; k = -1; for (j = 0; j < T.vexnum; j++) { if (closedge[j].lowcost != 0 && closedge[j].lowcost < min) { min = closedge[j].lowcost; k = j; } } return k; } void prim(AGraph T, int u) //起点为u { int i, j, k; Path closedge[MAX]; for (j = 0; j < T.vexnum; j++) { closedge[j].adjvex = u; closedge[j].lowcost = T.arc[u][j]; } closedge[u].lowcost = 0; // closedge[w].lowcost==0表示w已经加入生成树 for (i = 1; i < T.vexnum; i++) { k = minclosedge(closedge); printf("<%d,%d> ", closedge[k].adjvex, k); closedge[k].lowcost = 0; for (j = 0; j < T.vexnum; j++) { if (T.arc[k][j] < closedge[j].lowcost) { closedge[j].lowcost = T.arc[k][j]; closedge[j].adjvex = k; } } } } int main() { int i, j; printf("请输入图的顶点数:\n"); scanf_s("%d", &T.vexnum); printf("请%d阶输入邻接矩阵的值:\n", T.vexnum); for(i = 0; i < T.vexnum; i++) for (j = 0; j < T.vexnum; j++) scanf_s("%d", &T.arc[i][j]); prim(T, 0); //起点为0 system("pause"); }

编译环境: Visual Studio

你可能感兴趣的:(Data,Strutures,and,Algorithm)