//最小生成树
#include <iostream>
#include <stdio.h>
#include <queue>
using namespace std;
#define MAX_LINE 7
char tree[MAX_LINE][MAX_LINE]
={
{-1, 7, -1, 5, -1, -1, -1},
{7, -1, 8, 9, 7, -1, -1},
{-1, 8, -1, -1, 5, -1, -1},
{5, 9, -1, -1, 15, 6, -1},
{-1, 7, 5, 15, -1, 8, 9},
{-1,-1, -1, 6, 8,-1, 11},
{-1,-1, -1, -1, 9,11, -1}
};
typedef struct
{
char row;
char col;
} Line;
Line lines[MAX_LINE*MAX_LINE];
void prim();
char visit[MAX_LINE];//存储访问过的节点
char unvisited[MAX_LINE];//存储未被访问过的节点
char visitIndex,unvisitedIndex,linesIndex;
void init(){
//do something init
visitIndex=0;unvisitedIndex=0;linesIndex = 0;
char i;
//初始化未被访问节点
for(i = 0;i<MAX_LINE;i++){
visit[i] = i;
unvisited[i] = i;
}
}
int main()
{
init();
cout<<"prim算法最小生成树"<<endl;
prim();
getchar();
return 0;
}
//prim最小生成树
void prim(){
visit[visitIndex++] = 0;//将0节点放入访问数组
unvisited[0] = -1;
char i = 0,j,min;
char row,col,sum = 0;
Line tmpLine;
while(visitIndex<MAX_LINE)
{
min = 20;
for(i = 0;i<visitIndex;i++)
{
row = visit[i];//选出x
//寻找最小y
for(j = 0;j<MAX_LINE;j++)
{
if(unvisited[j] == -1)
continue;
col = unvisited[j];
if(tree[row][col] == -1)
continue;
if(tree[row][col] < min)
{
min = tree[row][col];
tmpLine.row = row;
tmpLine.col = col;
}
}
}
//找到最小min
lines[linesIndex++] = tmpLine;
visit[visitIndex++] = tmpLine.col;
unvisited[tmpLine.col] = -1;
sum+=min;
}
//打印path和sum
for(i = 0;i<linesIndex;i++)
printf("<%d,%d>\n",lines[i].row,lines[i].col);
printf("total num is %d\n",sum);
}
c++ 最小生成树之prim算法
最新推荐文章于 2024-06-26 17:12:22 发布