码迷,mamicode.com
首页 > 其他好文 > 详细

最小生成树-Prim算法

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

标签:prim

【问题】

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

【代码】

#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算法

标签:prim

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!