在这里说下最小连通网的Prim算法:
而Kruskal算法,有介绍,大家可以去看下!
Prim算法代码:
#include#include /* run this program using the console pauser or add your own getch, system("pause") or input loop */ #define VNUM 9 #define MV 65536 int P[VNUM];//记录边 int Cost[VNUM];//存储每一条边所要耗费的成本 int Mark[VNUM];//标记顶点 int Matrix[VNUM][VNUM] = {//图 {0, 10, MV, MV, MV, 11, MV, MV, MV}, {10, 0, 18, MV, MV, MV, 16, MV, 12}, {MV, 18, 0, 22, MV, MV, MV, MV, 8}, {MV, MV, 22, 0, 20, MV, 24, 16, 21}, {MV, MV, MV, 20, 0, 26, MV, 7, MV}, {11, MV, MV, MV, 26, 0, 17, MV, MV}, {MV, 16, MV, 24, MV, 17, 0, 19, MV}, {MV, MV, MV, 16, 7, MV, 19, 0, MV}, {MV, 12, 8, 21, MV, MV, MV, MV, 0}, }; void Prim(int sv) // O(n*n) { int i = 0;//循环变量 int j = 0;//循环变量 if( (0 <= sv) && (sv < VNUM) ) { for(i=0; i -1 ) {//如果为真,则说明照到最小值 Mark[index] = 1; printf("(%d, %d, %d)\n", P[index], index, Cost[index]); } for(j=0; j
~$ gcc -o prim prim.c
~$ ./prim (0, 1, 10) (0, 5, 11) (1, 8, 12) (8, 2, 8) (1, 6, 16) (6, 7, 19) (7, 4, 7) (7, 3, 16)