#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define INFINILY 10000000
#define MAXNODE 100
#define MAXNUM 100
typedef char VertexType;
struct
{
VertexType vex;
int lowcost;
}closedge[MAXNUM];
typedef struct
{
int adj;
}ArcType;//
typedef struct
{
VertexType vertexs[MAXNODE];
ArcType arcs[MAXNODE][MAXNODE];
int vexnum,arcnum;
}GraphType;//
int LocateVex(GraphType G,VertexType v)
{
int i,k;
for(k=0;k<G.vexnum;k++)
if(G.vertexs[k]==v)
{
i=k;
break;
}
return(i);
}
int CreateGraph(GraphType G)
{
int i,j,k,weight;
VertexType v1,v2;
printf("输入顶点数和弧数_,\n");
scanf("%d,%d",&G.vexnum,&G.arcnum);
for(i=0;i<G.vexnum;i++)
for(j=0;j<G.vexnum;j++)
G.arcs[i][j].adj=1000000;
printf("输入图的顶点 _ \n");
for(i=0;i<G.vexnum;i++)
scanf("%c",&G.vertexs[i]);
printf("输入弧的顶点和权值,_,_\n");
for(k=0;k<G.arcnum;k++)
{
printf("第%d组",k);
scanf("%c,%c,%d",&v1,&v2,&weight);
i=LocateVex(G,v1);
j=LocateVex(G,v2);
G.arcs[i][j].adj=weight;
G.arcs[j][i].adj=weight;
}
return(1);
}
void Prim(GraphType G,VertexType u)
{
int k,i,j,e,k0,mincost;
char u0,v0;
k=LocateVex(G,u);
closedge[k].lowcost=0;
for(i=0;i<G.vexnum;i++)
if(i!=k)
{
closedge[i].vex=u;
closedge[i].lowcost=G.arcs[k][i].adj;
}
for(e=1;e<=G.vexnum-1;e++)
{
mincost=100000000;
k0=0;
for(j=0;j<G.vexnum;j++)
if(closedge[j].lowcost!=0&&closedge[j].lowcost<mincost)
{
k0=j;
mincost=closedge[j].lowcost;
}
u0=closedge[k0].vex;
v0=G.vertexs[k0];
printf("(%c,%c)\n",u0,v0);
closedge[k0].lowcost=0;
for(i=0;i<G.vexnum;i++)
if(G.arcs[k0][i].adj<closedge[i].lowcost)
{
closedge[i].lowcost=G.arcs[k0][i].adj;
closedge[i].vex=v0;
}
}
}
void main()
{
GraphType G;
CreateGraph(G);
Prim(G,0);
}
int CreateGraph(GraphType G)
参数用形参的话,函数里是修改不了外部传入的G变量内容的。改为指针参数吧,或者把返回值改为GraphType类型
int CreateGraph(GraphType *G)
{
scanf("%d,%d",*G.vexnum,*G.arcnum);
.....
}
void main()
{
GraphType G;
CreateGraph(&G);
Prim(G,0);
}