【问题】
求一个给定的加权连通图的最小生成树问题。
【代码】
#include <stdio.h> #include <stdlib.h> #define MAXNUM 1000 #define MAX_VERTEX_NUM 20 typedef char Vertextype; typedef struct node { int weight; }Adjmatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; typedef struct { Vertextype vexs[MAX_VERTEX_NUM]; Adjmatrix arcs; int vexnum, arcnum; }Algraph; typedef struct { int start_vex; int end_vex; int weight; }Edge; void prim(Algraph G, int firstvex) { Edge E[MAXNUM]; Edge tmp; int vex_num; int m, t, w; int min = MAXNUM, i = 0, j = 0, k = 0; vex_num = G.vexnum; //初始化Edge for(i = 0; i < vex_num; i++) { E[i].start_vex = firstvex; if(i >= firstvex) { E[i].end_vex = i + 1; E[i].weight = G.arcs[firstvex][i+1].weight; } else { E[i].end_vex = i; E[i].weight = G.arcs[firstvex][i].weight; } } //对所有的顶点依次处理 for(i = 1; i < vex_num; i++) { min = MAXNUM; m = i - 1; //找出当前顶点的最小权重边 for(j = i - 1; j < vex_num - 1; j++) { if(E[j].weight < min) { min = E[j].weight; m = j; } } //依次将处理完的顶点放到前端 tmp = E[i - 1]; E[i - 1] = E[m]; E[m] = tmp; j = E[i - 1].end_vex; //更新权重 for(k = i; k < vex_num - 1; k++) { t = E[k].end_vex; w = G.arcs[j][t].weight; if(w < E[k].weight) { E[k].weight = w; E[k].start_vex = j; } } } }
原文:http://blog.csdn.net/jjjcainiao/article/details/25554111