void creat_graph(int vertice1,int vertice2)
{
int weight;
printf("请输入顶点%d到顶点%d的权值:",vertice1,vertice2);
scanf("%d",&weight);
cost[vertice1][vertice2]=weight;
cost[vertice2][vertice1]=weight;
}
void Prim(int edges[][N],int u)
{
int v,k,j,min;
for(v=1;v<=N;v++)
if(v!=u)
{
minedge[v].end=u;
minedge[v].len=edges[v][u];
}
minedge[u].len=0;
for(k=1;k<N;k++)
{
min=minedge[k].len;
v=k;
for(j=1;j<=N;j++)
if(minedge[j].len>0&&minedge[j].len<min)
{
min=minedge[j].len;
v=j;
}
if(min==32767)
{
printf("图不连通,无生成树!");
}
printf("起点:%d,终点:%d;\n",v,minedge[v].end);
minedge[v].len=-minedge[v].len;
for(j=1;j<=N;j++)
if(edges[j][v]<minedge[j].len)
{
minedge[j].len=edges[j][v];
minedge[j].end=v;
}
}
}
void main()
{
int source;
int destination;
int i,j;
for(i=1;i<=M;i++)
{
cost[i][j]=8;
if(j==i) cost[i][j]=0;
}
while(1)
{
printf("请输入起点和终点:");
scanf("%d,%d",&source,&destination);
if(source==-1||destination==-1)
break;
if(source==destination)
printf("错误:自身循环\n");
else if(source>M||destination>M)
printf("错误:超出范围\n");
else
creat_graph(source,destination);
}
printf("********************************\n");
printf("\n\n######
#图的矩阵形式#######\n\n");
print_graph();
printf("\n\n##########################\n\n");
printf("\n\n最小生成树:\n");
Prim(cost,0);
printf("\n");
}