// 采用边集数组表示图
//其中判断目前生成树是否已连通(有时无需遍历边集数组的全部元素) 的函数int IsCompleted(int *parent); 为自己加上去的
// 另外,简单起见,边集数组(按边的权值从小到大排序)在main函数中直接输入了
#include <stdio.h>
#include <stdlib.h>
#define MAXEDGE 10
#define MAXVEX 6
//边集数组表示图
struct Edge{
int a;
int b;
int weight;
};
struct MGraph{
int numVertexes;
int numEdges;
int *vex;
Edge *edges;
};
int Find(int *parent,int f)
{
while(parent[f]!=-1) //结点f与parent[f]是否连接(或者间接即多跳连接)着(在边子集中)同一个结点 ,注意!!此处是循环while而非判断if
f=parent[f];
return f;
}
int IsCompleted(int *parent)
{
int i;
int n=0;
for(i=0;i<MAXVEX;++i)
{
if(parent[i]!=-1)
++n;
}
if(n==MAXVEX-1) //最小生成树的特点是n各节点有n-1条边
return 1;
else
return 0;
}
void MiniSpanTree_Kruskal(MGraph *G)
{
int i,n,m;
//Edge edges[MAXEDGE]; //边集数组
int parent[MAXVEX]; //判断边与边之间是否形成环路,元素值parent[i]非0时表示结点i与parent[i]之间的边已确定为生成树的某一条边
for(i=0;i<G->numVertexes;++i)
parent[i]=-1;
//parent[i]=0;
for(i=0;i<G->numEdges;++i)
{
n=Find(parent,G->edges[i].a);
m=Find(parent,G->edges[i].b);
//if(n!=m && parent[n]!=m)
if(n!=m) //判断结点edges[i].a与edges[i].b是否连接(或者间接即多跳连接)着(在边子集中)同一个结点,
//注意:假设结点edges[i].a与结点edges[i].b都跟量外一个结点X相连(或者间接相连),如若不加判断,则三个结点会形成回路
{
parent[n]=m;
printf("(%d,%d) %d\n",G->edges[i].a,G->edges[i].b,G->edges[i].weight);
}
//怎么判断生成树已连通原图,即已生成生成树
if(IsCompleted(parent))
return;
}
}
void main()
{
MGraph *my_g=(struct MGraph*)malloc(sizeof(struct MGraph));
int i,j;
int t=0;
my_g->numVertexes=6;
my_g->numEdges=10;
my_g->vex=(int*)malloc(sizeof(char)*my_g->numVertexes);
if(!my_g->vex) return;
for(i=0;i<my_g->numVertexes;++i) //一维数组(图中各结点编号)初始化{0,1,2,3,4,5}
my_g->vex[i]=i;
my_g->edges=(Edge*)malloc(sizeof(Edge)*MAXEDGE);
if(!my_g->edges) return;
//简单起见,边集数组(按边的权值从小到大排序)直接输入
my_g->edges[0].a=0; my_g->edges[0].b=2; my_g->edges[0].weight=1;
my_g->edges[1].a=3; my_g->edges[1].b=5; my_g->edges[1].weight=2;
my_g->edges[2].a=1; my_g->edges[2].b=4; my_g->edges[2].weight=3;
my_g->edges[3].a=2; my_g->edges[3].b=5; my_g->edges[3].weight=4;
my_g->edges[4].a=0; my_g->edges[4].b=3; my_g->edges[4].weight=5;
my_g->edges[5].a=1; my_g->edges[5].b=2; my_g->edges[5].weight=5;
my_g->edges[6].a=2; my_g->edges[6].b=4; my_g->edges[6].weight=5;
my_g->edges[7].a=0; my_g->edges[7].b=1; my_g->edges[7].weight=6;
my_g->edges[8].a=4; my_g->edges[8].b=5; my_g->edges[8].weight=6;
my_g->edges[9].a=2; my_g->edges[9].b=3; my_g->edges[9].weight=7;
MiniSpanTree_Kruskal(my_g);
}