首先将其转化为邻接矩阵;
然后设置一个辅助数组included[],用来记录该顶点是否被访问,初始化为0;
设置 一个数组previous[],用来代表访问的前驱,初始化为-1;
设置distance[]数组用来存各边的距离。
i |
0 |
1 |
2 |
3 |
4 |
5 |
Included[i] |
1 |
0 |
0 |
0 |
0 |
0 |
previous[i] |
-1 |
-1 |
-1 |
-1 |
-1 |
-1 |
初始时,从v1开始,此时included[0]=1;再从与v1的相连的边中找出一条权值最小的边,即顶点v3,与v1的距离为1,此时修改辅助数组included[2]=1,且previous[2]=0;然后继续循环,寻找权值最小的边,依此类推,直到included[]数组全部为1 ,即扫描完毕,最小生成树完成,打印出生成树的各边。
#include <stdio.h>
#include <malloc.h>
#define INF 1000
#define NODES 6
//The network
int network[6][6] = {
{ 0, 6, 1, 5, INF, INF },
{ 6, 0, 5, INF, 3, INF },
{ 1, 5, 0, 5, 6, 4 },
{ 5, INF, 5, 0, INF, 2 },
{ INF, 3, 6, 5, 0, 6 },
{ INF, INF, 4, 2, 6, 0 } };
//Previous node
int previous[6] = { -1, -1, -1, -1, -1, -1 };
//Is the current included?
int included[6] = { 0, 0, 0, 0, 0, 0 };
//Minimal distance from the existing set
int distance[6];
void prim(int paraStartNode)
{
int i, j;
int tempMin;
int tempNewNode;
//Initialize the previous vector.
for (i = 0; i < NODES; i++)
{
//The previous node is always the start node.
previous[i] = paraStartNode;
//The distance is the distance from the start node.
distance[i] = network[paraStartNode][i];
}//Of for i
previous[paraStartNode] = -1;
//Only the start node is included
included[paraStartNode] = 1;
//Add the other nodes one by one
for (i = 0; i < NODES - 1; i++)
{
//Find one node to add
tempMin = INF;
tempNewNode = -1;
for (j = 0; j < NODES; j++) {
if (!included[j]) {
if (tempMin > distance[j]) {
tempMin = distance[j];
tempNewNode = j;
}//Of if
}//Of if
}//Of for j
//Add the node
included[tempNewNode] = 1;
//Serve for others
for (j = 0; j < NODES; j++) {
if (!included[j]) {
if (distance[j] > network[tempNewNode][j]) {
distance[j] = network[tempNewNode][j];
previous[j] = tempNewNode;
}//Of if
}//Of if
}//Of for j
}//Of for i
}//Of prim
void printTree() {
int i;
for (i = 0; i < NODES; i++) {
printf("The previous node of %d is %d\r\n", i, previous[i]);
}//Of for i
}//Of printTree
int main() {
prim(0);
printTree();
return 0;
}