#include <stdio.h> #define N 6 #define TRUE 1 #define FALSE 0 #define MAX_VALUE 9999 typedef struct edge{ int from; int to; float weight; }edge; edge path[N]; //保存第1到N-1步的走法 float c[N+1][N+1]; //保存邻接矩阵信息 int closest[N+1]; //保存在S中 离 j最近的顶点编号 float lowcost[N+1]; //lowcost[j] = c[j][closest[j]] 就是 j到S中最近顶点的距离 int s[N+1]; //标志一个顶点是否加入到最小生成树中 void prim(){ int i; s[1] = TRUE; //顶点 1放入最小生成树中 for(i=2;i<=N;i++){ //初始化 lowcost[i] = c[1][i]; //任何一点到S集合的最小距离,也就等同于到顶点1的距离,因为S中只有1一个顶点 closest[i] = 1; //任何一点到S集合中的顶点 1 最近(因为S集合中只有顶点1) s[i] = FALSE; //任何顶点都没有加入到S集合中 } int pf = 1; for(i=1;i<N;i++){ float min = MAX_VALUE; int j = 1; for(int k=2;k<=N;k++){ //选出一个未选入最小生成树的顶点,该顶点离S中顶点的距离最小 if(lowcost[k]<min && (!s[k])){ min = lowcost[k]; j=k; } } printf("%d , %d/n",j,closest[j]); path[pf].from = j; path[pf].to = closest[j]; path[pf].weight = c[j][closest[j]]; pf++; s[j] = TRUE; for(k=2;k<=N;k++){ //针对所有未选入最小生成树的顶点,进行更新 if(c[j][k] < lowcost[k] && (!s[k])){ lowcost[k] = c[j][k]; closest[k] = j; } } } } void main(){ c[1][1] = MAX_VALUE; //顶点1 c[1][2] = 6; c[1][3] = 1; c[1][4] = 5; c[1][5] = MAX_VALUE; c[1][6] = MAX_VALUE; c[2][1] = 6; //顶点2 c[2][2] = MAX_VALUE; c[2][3] = 5; c[2][4] = MAX_VALUE; c[2][5] = 3; c[2][6] = MAX_VALUE; c[3][1] = 1; //顶点3 c[3][2] = 5; c[3][3] = MAX_VALUE; c[3][4] = 5; c[3][5] = 6; c[3][6] = 4; c[4][1] = 5; //顶点4 c[4][2] = MAX_VALUE; c[4][3] = 5; c[4][4] = MAX_VALUE; c[4][5] = MAX_VALUE; c[4][6] = 2; c[5][1] = MAX_VALUE; //顶点5 c[5][2] = 3; c[5][3] = 6; c[5][4] = MAX_VALUE; c[5][5] = MAX_VALUE; c[5][6] = 6; c[6][1] = MAX_VALUE; //顶点6 c[6][2] = MAX_VALUE; c[6][3] = 4; c[6][4] = 2; c[6][5] = 6; c[6][6] = MAX_VALUE; prim(); printf("-------------------------------------------/n"); printf("The path is: /n"); for(int i = 1;i<N;i++){ printf("%d----%d Weigth: %.2f /n",path[i].from,path[i].to,path[i].weight); } }