在這裏說下最小連通網的Prim算法:算法
而Kruskal算法,http://blog.csdn.net/nethanhan/article/details/10050735有介紹,你們能夠去看下!數組
Prim算法代碼:oop
#include <stdio.h> #include <stdlib.h> /* 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<VNUM; i++) { Cost[i] = Matrix[sv][i];//初始動點與其它頂點相連邊的權值賦給cost數組 P[i] = sv;//保存邊 Mark[i] = 0;//初始化標記 } Mark[sv] = 1;//標記頂點 for(i=0; i<VNUM; i++) { int min = MV; int index = -1; for(j=0; j<VNUM; j++) {//挑選最小權值的邊 if( !Mark[j] && (Cost[j] < min) ) {//挑選完畢之後,index保存另外一個頂點 min = Cost[j]; index = j; } } if( index > -1 ) {//若是爲真,則說明照到最小值 Mark[index] = 1; printf("(%d, %d, %d)\n", P[index], index, Cost[index]); } for(j=0; j<VNUM; j++) {//從剛纔被標記的頂點做爲起始頂點 if( !Mark[j] && (Matrix[index][j] < Cost[j]) ) {//而後重新的起始頂點與其餘頂點(非標記頂點)相連邊的權值中尋找更小的,更新cost數組 Cost[j] = Matrix[index][j]; P[j] = index;//若是有其它更小的,那麼此邊的起始頂點爲P[i],也就是index,權值保存在cost數組中 } } } } } int main(int argc, char *argv[]) { Prim(0); return 0; }
~$ 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)this