#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define INF 32767
#define MAVX 100
typedef int InfoType;
typedef int Vertex;
typedef struct
{
int no;
InfoType info;
}VertexType;
typedef struct
{
int edges[MAVX][MAVX];
int vexnum,arcnum;
VertexType vexs[MAVX];
}MGraph;
typedef struct ANode
{
int adjvex;
struct ANode *nextarc;
InfoType info;
}ArcNode;
typedef struct Vnode
{
Vertex data;
ArcNode *firstarc;
}VNode;
typedef VNode AdjList[MAVX];
typedef struct
{
AdjList adjlist;
int n,e;
}ALGraph;
int visited[MAVX];
void MatToList(MGraph g,ALGraph * &G)
{
int i,j,n=g.vexnum;
ArcNode *p;
G=(ALGraph *)malloc(sizeof(ALGraph));
for(i=0;i<n;i++)
G->adjlist[i].firstarc=NULL;
for(i=0;i<n;i++)
for(j=n-1;j>=0;j--)
if(g.edges[i][j]!=0)
{
p=(ArcNode *)malloc(sizeof(ArcNode));
p->adjvex=j;
p->info=g.edges[i][j];
p->nextarc=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
}
G->n=n;
G->e=g.arcnum;
}
void DispMat(MGraph g)
{
int i,j;
for(i=0;i<g.vexnum;i++)
{
for(j=0;j<g.vexnum;j++)
if(g.edges[i][j]==INF)
printf("%3s","∞");
else
printf("%3d",g.edges[i][j]);
printf("\n");
}
}
void DispAdj(ALGraph *G)
{
int i;
ArcNode *p;
for(i=0;i<G->n;i++)
{
p=G->adjlist[i].firstarc;
if(p!=NULL)printf("%3d:",i);
while(p!=NULL)
{
printf("%3d",p->adjvex);
p=p->nextarc;
}
printf("\n");
}
}
void Prim(MGraph g,int v)
{
int lowcost[MAVX],min,n=g.vexnum;
int closest[MAVX],i,j,k;
for(i=0;i<n;i++)
{
lowcost[i]=g.edges[v][i];
closest[i]=v;
}
for(i=1;i<n;i++)
{
min=INF;
for(j=0;j<n;j++)
if(lowcost[j]!=0 && lowcost[j]<min)
{
min=lowcost[j];k=j;
}
printf("边(%d,%d)权为:%d\n",closest[k],k,min);
lowcost[k]=0;
for(j=0;j<n;j++)
if(g.edges[k][j]!=0 && g.edges[k][j]<lowcost[j])
{
lowcost[j]=g.edges[k][j];
closest[j]=k;
}
}
}
int main()
{
int i,j;
MGraph g;
int A[MAVX][11];
g.vexnum=6;
g.arcnum=9;
for(i=0;i<g.vexnum;i++)
for(j=0;j<g.vexnum;j++)
A[i][j]=INF;
A[0][1]=5; A[0][2]=8;A[0][3]=7; A[0][5]=3;
A[1][2]=4;
A[2][3]=5;A[2][5]=9;
A[3][4]=5;
A[4][5]=1;
for(i=0;i<g.vexnum;i++)
for(j=0;j<g.vexnum;j++)
A[j][i]=A[i][j];
for(i=0;i<g.vexnum;i++)
for(j=0;j<g.vexnum;j++)
g.edges[i][j]=A[i][j];
printf("\n");
printf("图G的邻接矩阵:\n");
DispMat(g);
printf("\n");
printf("Prim(普利姆)算法求解结果:\n");
Prim(g,0);
printf("\n\n");
return 0;
}
数据结构源码笔记(C语言描述)汇总: