首页 > 其他 > 详细

最小生成树-Prim算法

时间:2014-05-13 23:55:18      阅读:549      评论:0      收藏:0      [点我收藏+]

【问题】

求一个给定的加权连通图的最小生成树问题。

【代码】

#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;
			}
		}

	}

}



最小生成树-Prim算法,布布扣,bubuko.com

最小生成树-Prim算法

原文:http://blog.csdn.net/jjjcainiao/article/details/25554111

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!