转自 http://blog.csdn.net/hustspy1990/article/details/6043698
1. 邻接矩阵存储
- //图的邻接矩阵存储表示
- #define INFINITY INT_MAX
- #define MAX_VERTEX_NUM 20
- typedef enum {DG, DN, UDG, UDN} GraphKind; //{有向图,有向网,无向图,无向网}
- typedef enum {OK, ERROR} Status;
- typedef struct ArcCell{
- int adj; //顶点关系类型。对于无权图,用0或1表示相邻否。对于有权图,则为权值类型。
- string info; //该弧所携带的信息
- }ArcCell, AdjMatrix;
- typedef struct {
- int vexs[MAX_VERTEX_NUM]; //顶点向量
- AdjMatrix arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //邻接矩阵
- int vexnum, arcnum; //图的当前顶点数和弧数
- GraphKind kind; //图的种类标志
- }MGraph;
- bool visited[MAX_VERTEX_NUM]; //设访问标志数组,供遍历时使用
- //Prim算法-记录从顶点集U到V-U的代价最小的边的辅助数组定义
- struct {
- int adjvex;
- int lowcost;
- }closedge[MAX_VERTEX_NUM];
2. Prim算法
- void MiniSpanTree_PRIM(MGraph G, int u)
- {
- //用普里姆Prim算法从第u个顶点出发,构造网G的最小生成树T,输出T的各条边
- //记录从顶点集U到V-U的代价最小的边的辅助数组定义
- // struct {
- // int adjvex;
- // int lowcost;
- // }closedge[MAX_VERTEX_NUM];
- int i,j,k;
- for(j=0; j<G.vexnum; ++j) //辅助数组初始化
- if(j!=u)
- {
- closedge[j].adjvex = u;
- closedge[j].lowcost = G.arcs[u][j].adj;
- }
- closedge[u].lowcost = 0; //初始化U={u}
- for(i=0; i<G.vexnum; ++i)
- {
- int min = INT_MAX;
- k=-1;
- for(j=0; j<G.vexnum; ++j) //求出最小生成树的下一个顶点k
- if(closedge[j].lowcost >0 && closedge[j].lowcost < min)
- {
- k = j;
- min = closedge[j].lowcost;
- }//if
- if(k <0)
- return;
- cout<<closedge[k].adjvex<<"——"<<G.vexs[k]<<" : "<<closedge[k].lowcost<<endl; //输出生成树的边
- closedge[k].lowcost = 0; //第k顶点并入U集
- for(j=0; j<G.vexnum; ++j)
- if(G.arcs[k][j].adj < closedge[j].lowcost) //新顶点并入U后,重新选择最小边
- {
- closedge[j].adjvex = G.vexs[k];
- closedge[j].lowcost = G.arcs[k][j].adj;
- }
- }
- }//MiniSpanTree_PRIM
3. 构造一个测试用的无向网
- void CreateUDNTest(MGraph &G)
- { //构造一个测试用的无向网
- int i,j;
- //数组a[10][3]存放“边”和对应的权值
- int a[10][3] = { {0, 1, 6}, {0, 2, 1}, {0, 3, 5},
- {1, 2, 5}, {1, 4, 3}, {2, 3, 5}, {2, 4, 6}, {2, 5, 4},
- {4, 5, 6}, {3, 5, 2}
- };
- G.kind = UDN;
- G.vexnum = 6;
- G.arcnum = 10;
- for(i=0; i<G.vexnum; ++i) //构造顶点向量
- G.vexs[i] = i;
- for(i=0; i<G.vexnum; ++i) //初始化为全INT_MAX
- for(j=0; j<G.vexnum; ++j)
- {
- G.arcs[i][j].adj = INT_MAX;
- G.arcs[i][j].info = "";
- }
- for(i=0; i<G.arcnum; ++i) //对存在的边赋值
- G.arcs[a[i][0]][a[i][1]].adj = G.arcs[a[i][1]][a[i][0]].adj = a[i][2];
- }
4.主函数
- int main()
- {
- MGraph gra2;
- CreateUDNTest(gra2); //构造无向网G
- cout<<"构造最小生成树:"<<endl;
- MiniSpanTree_PRIM(gra2, 0);
- return 0;
- }