算法的内容原理比较好理解,我想说的是我在编代码的时候理解上遇到的问题,关于vexs和weight 两个数组的用途,weigh用来标记那个顶点已经访问过了,所以不能用简单的一个大for 要确保weight的作用
#define MAX_VEX 6
#define MAX_ARC 6
typedef enum { DG, DN, UDG, UDN } Graphkind;
typedef struct {
int adj;
int info;
}Arcnode;
typedef struct {
char vexs[MAX_VEX];
Arcnode arcs[MAX_VEX][MAX_VEX];
int vex_num, arc_num;
Graphkind kind;
}AdjMatriax;
void createDN(AdjMatriax *G, char *a) {
G->arc_num = MAX_ARC;
G->vex_num = MAX_VEX;
int i, j;
for (i = 0; i < G->vex_num; i++) {
for (j = 0; j < G->vex_num; j++) {
G->arcs[i][j].adj = 0;
G->arcs[i][j].info = 65535;
}
}
for (i = 0; i < G->vex_num; i++) {
G->vexs[i] = a[i];
}
int k;
int u, v, weight;
for (k = 0; k < G->vex_num; k++) {
switch (k)
{
case 0: v = 1, u = 2, weight = 2; break;
case 1: v = 1, u = 4, weight = 1; break;
case 2: v = 2, u = 3, weight = 3; break;
case 3: v = 2, u = 5, weight = 4; break;
case 4: v = 3, u = 4, weight = 5; break;
case 5: v = 3, u = 5, weight = 6; break;
default:
break;
}
G->arcs[v - 1][u - 1].adj = 1;
G->arcs[v - 1][u - 1].info = weight;
G->arcs[u - 1][v - 1].adj = 1;
G->arcs[u - 1][v - 1].info = weight;
}
Graphkind kind = UDN;
}
void Prim(AdjMatriax *G) {
char vex[MAX_VEX];
int weight[MAX_VEX];
int start = 2;//*************************************设置开始点
int i, j, k, m = 0;
int min;
for (i = 0; i < G->vex_num; i++) {//赋予编号start的权值
weight[i] = G->arcs[start][i].info;
}
weight[start] = 0;//出发点的权值为零
vex[m] = G->vexs[start];//出存第一个点
for (i = 0; i < G->vex_num-1; i++) {
min = 65535;
for (j = 0; j < G->vex_num; j++) {
if (weight[j] < min&&weight[j] != 0) {//出发点的个链接边的最小权值
min = weight[j];
k = j;//k记录最小全职的点
}
}
printf("%c 距离最近的点为 %c 距离为%d\n", vex[i], G->vexs[k],min);
vex[++m] = G->vexs[k];//vex的下一个点---储存权值最小的点
weight[k] = 0;
for (j = 0; j < G->vex_num; j++) {
if (weight[j] && G->arcs[k][j].info != 65535) {
weight[j] = G->arcs[k][j].info;
}
}
}
for (i = 0; i < G->vex_num-1; i++) {
printf("%c ", vex[i]);
}
system("pause");
}
int main()
{
AdjMatriax *G = (AdjMatriax*)malloc(sizeof(AdjMatriax));
char a[6] = "ABCDE";
createDN(G, a);
Prim(G);
return 0;
}