最小生成树克鲁斯卡尔算法c语言实现__Kruskal

// 采用边集数组表示图

//其中判断目前生成树是否已连通(有时无需遍历边集数组的全部元素) 的函数int IsCompleted(int *parent); 为自己加上去的

// 另外,简单起见,边集数组(按边的权值从小到大排序)在main函数中直接输入了


#include 
#include 

#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;inumVertexes;++i)
		parent[i]=-1;
		//parent[i]=0;

	for(i=0;inumEdges;++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;inumVertexes;++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);  
}  



最小生成树克鲁斯卡尔算法c语言实现__Kruskal_第1张图片


你可能感兴趣的:(数据结构与算法分析)