1、普里姆算法:https://www.cnblogs.com/biyeymyhjob/archive/2012/07/30/2615542.html
2、Prim算法核心:在当前已经遍历到的权值中选择最小的权值生成树
#include
#include
#define MAXVALUE 100
#define INITVALUE 65535
typedef struct
{
char vexs[MAXVALUE];
int arc[MAXVALUE][MAXVALUE];
int numVexs, numArc;
}MGraph;
int visited[MAXVALUE]; //定义是否遍历过的点的数组标志位
void CreatGraph (MGraph *G)
{
int i, j, k, weight;
printf("Enter numVexs & numArc:");
scanf("%d%d", &(G->numVexs), &(G->numArc));
for(i = 0; i < G->numVexs; i++)
{
printf("Enter %d vex:", i);
getchar();
scanf("%c", &(G->vexs[i]));
}
for(i = 0; i < G->numVexs; i++) //邻接矩阵初始化
{
for(j = 0; j < G->numVexs; j++)
{
G->arc[i][j] = INITVALUE;
}
}
for(k = 0; k < G->numArc; k++)
{
printf("Enter i, j, weight:");
scanf("%d%d%d", &i, &j, &weight);
G->arc[i][j] = weight;
G->arc[j][i] = weight;
}
}
void DFS (MGraph *G, int i)
{
int j;
visited[i] = 1;
printf("%c\n", G->vexs[i]);
for(j = 0; j < G->numVexs; j++)
{
if(G->arc[i][j] != INITVALUE && !visited[j])
{
DFS(G, j); //对未遍历的结点进行DFS
}
}
}
void DFSTravers (MGraph *G)
{
int i;
for(i = 0; i < G->numVexs; i++)
{
visited[i] = 0;
}
for(i = 0; i < G->numVexs; i++)
{
if(!visited[i])
{
DFS(G, i); //如果是连通图,则只需要DFS一次
}
}
}
void PrintGraph (MGraph *G)
{
int i, j;
for(i = 0; i < G->numVexs; i++)
{
for(j = 0; j < G->numVexs; j++)
{
printf("%d ", G->arc[i][j]);
}
printf("\n");
}
}
void MiniSpanTree (MGraph G)
{
int i, j, minval, k;
int adjvex[MAXVALUE]; //定义数组,存储权值边的起点下标
int lowest[MAXVALUE];
lowest[0] = 0;
adjvex[0] = 0;
for(i = 1; i < G.numVexs; i++)
{
adjvex[i] = 0;
lowest[i] = G.arc[0][i];
}
for(i = 0; i < G.numVexs; i++)
{
minval = INITVALUE;
j = 1;
k = 0;
while(j < G.numVexs) //找到当前边中权值最小的边
{
if(lowest[j] < minval && lowest[j] != 0)
{
minval = lowest[j];
k = j;
}
j++;
}
lowest[k] = 0;
printf("(%d %d)", adjvex[k], k);
for(j = 1; j < G.numVexs; j++) //将权值较小的边加入Lowest数组中
{
if(G.arc[k][j] < lowest[j] && lowest[j] != 0)
{
lowest[j] = G.arc[k][j];
adjvex[j] = k;
}
}
}
}
int main ()
{
MGraph G;
CreatGraph(&G);
// DFSTravers(&G);
// PrintGraph(&G);
MiniSpanTree(G);
return 0;
}