关闭

Prim算法C语言实现

标签: Prim算法
391人阅读 评论(0) 收藏 举报
分类:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define NUM 6

typedef struct Node
{
     int num;
     int data;
} Node;
typedef struct MGraph
{
     int edges[NUM][NUM];
     int n,e;
} MGraph;

MGraph *build_graph();
void Prim(MGraph *mgraph, int v);

int main(void )
{
     MGraph *mgraph;

     mgraph=build_graph();
     Prim(mgraph, 0);
     return 0;
}

MGraph *build_graph()
{
     MGraph *mgraph;
     int i,j;
     int this_edges=0;
     int arrays[NUM][NUM]={{0,6,1,5,INT_MAX,INT_MAX},
			   {6,0,5,INT_MAX,3,INT_MAX},
			   {1,5,0,5,6,4},
			   {5,INT_MAX,5,0,INT_MAX,2},
			   {INT_MAX,3,6,INT_MAX,0,6},
			   {INT_MAX,INT_MAX,4,2,6,0}};
     mgraph=(MGraph *)malloc(sizeof(MGraph));
     for(i=0;i<NUM;i++)
     {
	  for(j=0;j<NUM;j++)
	  {
	       mgraph->edges[i][j]=arrays[i][j];
	       if(arrays[i][j]!=0 && arrays[i][j]!=INT_MAX)
	       {
		    this_edges++;
	       }
	  }
     }
     mgraph->n=NUM;
     mgraph->e=this_edges;

     printf("node=%d,edges=%d\n",mgraph->n,mgraph->e);
     for(i=0;i<NUM;i++)
     {
	  for(j=0;j<NUM;j++)
	  {
	       if(mgraph->edges[i][j]!=INT_MAX)
	       {
		    printf("%3d",mgraph->edges[i][j]);
	       }
	       else
	       {
		    printf("%3c",'&');
	       }
	  }
	  printf("\n");
     }
     
     return mgraph;
     
}
void Prim(MGraph *mgraph, int v)
{
     int i,j;
     int min,index;
     int dis[NUM];
     int pre[NUM];

     for(i=0;i<mgraph->n;i++)
     {
	  dis[i]=mgraph->edges[v][i];
	  pre[i]=v;
     }


     for(j=1;j<mgraph->n;j++)
     {
	  min=INT_MAX;
	  index=v;	  
	  for(i=0;i<mgraph->n;i++)
	  {
	       if(dis[i]!=0 && dis[i]!=INT_MAX)
	       {
		    if(dis[i]<min)
		    {
			 min=dis[i];
			 index=i;
		    }
	       }
	  }
	  printf("%d-%d:%d\n",pre[index],index,min);

	  for(i=0;i<mgraph->n;i++)
	  {
	       if(mgraph->edges[i][index]<dis[i])
	       {
		    dis[i]=mgraph->edges[i][index];
		    pre[i]=index;
	       }
	  }
     }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:15646次
    • 积分:1057
    • 等级:
    • 排名:千里之外
    • 原创:93篇
    • 转载:1篇
    • 译文:1篇
    • 评论:1条
    最新评论