用c写最小生成树的算法
用c写最小生成树的算法
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define EMPTY_NUM 80
#define MAX_VERTEX_NUM 20
typedef char Vertex_Type[5];
typedef struct AdjMatrix
{
int weight;
}Adj_Matrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedef struct
{
Vertex_Type vertexs_vectors[MAX_VERTEX_NUM];
Adj_Matrix arcs;
int arc_num;
int vertex_num;
}AMGraph;
struct
{
Vertex_Type adj_vertex;
int lowcost;
}closedge[MAX_VERTEX_NUM];
void Init_UDN( AMGraph &G )
{
printf("输入图的弧的数量:");
scanf("%d", &G.arc_num);
printf("输入图的顶点数:");
scanf("%d", &G.vertex_num);
int j, i;
printf("输入顶点向量:");
for( i=0; i<G.vertex_num; ++i )
scanf("%s", G.vertexs_vectors[i]);
for( i=0; i<G.vertex_num; ++i )
for( j=0; j<G.vertex_num; ++j )
G.arcs[i][j].weight = G.arcs[j][i].weight = EMPTY_NUM;
}
int Get_Vertex_Location( AMGraph G, Vertex_Type v )
{
int i;
for( i=0; i<G.vertex_num; ++i )
if( strcmp(G.vertexs_vectors[i], v) == 0 )
break;
return i;
}
void Create_UDN( AMGraph &G )
{
Init_UDN( G );
Vertex_Type v1, v2;
int i, v1_site, v2_site, w;
printf("输入图的弧和权值(v1 -- v2 ,3):\n");
for( i=0; i<G.arc_num; ++i )
{
scanf("%s %*s %s ,%d", v1, v2, &w);
v1_site = Get_Vertex_Location( G, v1 );
v2_site = Get_Vertex_Location( G, v2 );
G.arcs[v1_site][v2_site].weight = G.arcs[v2_site][v1_site].weight = w;
}
}
void Print_Graph( AMGraph G )
{
for(int i=0; i<G.vertex_num; ++i )
{
for(int j=0; j<G.vertex_num; ++j )
printf(" %d ", G.arcs[i][j].weight);
printf("\n");
}
}
int Min_Num( AMGraph G )
{
int j = -1;
for( int i=0; i<G.vertex_num; ++i )
{
if( closedge[i].lowcost > 0 && j == -1 )
j = i;
if( closedge[i].lowcost> 0 && j != -1 && closedge[j].lowcost > closedge[i].lowcost )
j = i;
}
return j;
}
void MininSpanTree_Prim( AMGraph G, Vertex_Type V )
{
int k = Get_Vertex_Location( G, V );
for( int j=0; j<G.vertex_num; ++j )
{
closedge[j].lowcost = G.arcs[k][j].weight;
strcpy( closedge[j].adj_vertex, V );
}
closedge[k].lowcost = 0;
for( int i=1; i<G.vertex_num; ++i )
{
k = Min_Num( G );
closedge[k].lowcost = 0;
printf("%s--%s ", closedge[k].adj_vertex, G.vertexs_vectors[k] );
for( int j = 0; j<G.vertex_num; ++j )
if( closedge[j].lowcost > G.arcs[k][j].weight )
{
closedge[j].lowcost = G.arcs[k][j].weight;
strcpy( closedge[j].adj_vertex, G.vertexs_vectors[k] );
}
}
}
int main()
{
AMGraph G;
Vertex_Type v;
Create_UDN( G );
Print_Graph( G );
printf("输入从哪个点开始:");
scanf("%s", v);
MininSpanTree_Prim( G, v );
printf("\n");
return 0;
}