数据结构和算法(14)- 最小生成树(普里姆和克鲁斯卡尔算法)

489 阅读8分钟

一. 最小生成树

假设要在n个城市之间建立通信联络网,那么连通n个城市,只需要n-1条线路。其中网的顶点表示城市,边表示两城市之间的线路,赋予边的全职标识相应的代价。对于n个顶点的连通网可以建立许多不同的生成树,每一个生成树都可以是一个通信网。最合理的通信网应该是代价之和最小的生成树。在一个连通网的所有生成树中,各边的代价之和最小的那颗生成树称为改连通网的最小代价生成树(Minimum Cost Spanning Tree),简称为最小生成树

二. 普里姆(Prim)算法

1.算法构造过程:
  • 辅助数组adjvex[MAXVEX]存储相关顶点坐标,假设:adjvex[2] = 3意味着:图中顶点2顶点3是连通的
  • 辅助数组lowcost[MAXVEX]保存相关顶点间边的权值,如果lowcost[1] = 0,表示该顶点1已被选择加入到了图中
  • 首先选择顶点V0加入到图中,初始化两个数组,此时adjvex中存储的都是0lowcost中存储与V0有关的权值
  • 遍历剩余顶点
  • 循环查找lowcost中最小的权值,记录顶点k
  • 打印当前最小的权值G.arc[adjvex[k]][k],打印相关顶点
  • 标记lowcost[k] = 0,表示顶点k已加入到最小生成树
  • 循环所有顶点,找到与顶点k相连接的顶点,将对应的权值与lowcost中的权值比较,找到最小的顶点j,更新lowcost[j] = G.arc[k][j]adjvex[j] = k;
  • 继续遍历剩余顶点,直至所有顶点遍历完成
2.基础设置
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXEDGE 20
#define MAXVEX 20
#define INFINITYC 65535
typedef int Status;    /* Status是函数的类型,其值是函数结果状态代码,如OK等 */
typedef struct
{
    int arc[MAXVEX][MAXVEX];
    int numVertexes, numEdges;
}MGraph;
/*9.1 创建邻接矩阵*/
void CreateMGraph(MGraph *G)/* 构件图 */
{
    int i, j;
    /* printf("请输入边数和顶点数:"); */
    G->numEdges=15;
    G->numVertexes=9;
    for (i = 0; i < G->numVertexes; i++)/* 初始化图 */
    {
        for ( j = 0; j < G->numVertexes; j++)
        {
            if (i==j)
                G->arc[i][j]=0;
            else
                G->arc[i][j] = G->arc[j][i] = INFINITYC;
        }
    }
    G->arc[0][1]=10;
    G->arc[0][5]=11;
    G->arc[1][2]=18;
    G->arc[1][8]=12;
    G->arc[1][6]=16;
    G->arc[2][8]=8;
    G->arc[2][3]=22;
    G->arc[3][8]=21;
    G->arc[3][6]=24;
    G->arc[3][7]=16;
    G->arc[3][4]=20;
    G->arc[4][7]=7;
    G->arc[4][5]=26;
    G->arc[5][6]=17;
    G->arc[6][7]=19;
    for(i = 0; i < G->numVertexes; i++)
    {
        for(j = i; j < G->numVertexes; j++)
        {
            G->arc[j][i] =G->arc[i][j];
        }
    }
}
3.核心算法
/* Prim算法生成最小生成树 */
void MiniSpanTree_Prim(MGraph G)
{
    int min, i, j, k;
    int sum = 0;
    /* 保存相关顶点下标 */
    int adjvex[MAXVEX];
    /* 保存相关顶点间边的权值 */
    int lowcost[MAXVEX];
    /* 初始化第一个权值为0,即v0加入生成树 */
    /* lowcost的值为0,在这里就是此下标的顶点已经加入生成树 */
    lowcost[0] = 0;
    /* 初始化第一个顶点下标为0 */
    adjvex[0] = 0;
    //1. 初始化
    for(i = 1; i < G.numVertexes; i++)    /* 循环除下标为0外的全部顶点 */
    {
        lowcost[i] = G.arc[0][i];    /* 将v0顶点与之有边的权值存入数组 */
        adjvex[i] = 0;             /* 初始化都为v0的下标 */
    }
    //2. 循环除了下标为0以外的全部顶点, 找到lowcost数组中最小的顶点k
    for(i = 1; i < G.numVertexes; i++)
    {
        /* 初始化最小权值为∞, */
        /* 通常设置为不可能的大数字如32767、65535等 */
        min = INFINITYC;
        j = 1;k = 0;
        while(j < G.numVertexes)    /* 循环全部顶点 */
        {
            /* 如果权值不为0且权值小于min */
            if(lowcost[j]!=0 && lowcost[j] < min)
            {
                /* 则让当前权值成为最小值,更新min */
                min = lowcost[j];
                /* 将当前最小值的下标存入k */
                k = j;
            }
            j++;
        }
        /* 打印当前顶点边中权值最小的边 */
        printf("(V%d, V%d)=%d\n", adjvex[k], k ,G.arc[adjvex[k]][k]);
        sum+=G.arc[adjvex[k]][k];
        /* 3.将当前顶点的权值设置为0,表示此顶点已经完成任务 */
        lowcost[k] = 0;
        /* 循环所有顶点,找到与顶点k 相连接的顶点
         1. 与顶点k 之间连接;
         2. 该结点没有被加入到生成树;
         3. 顶点k 与 顶点j 之间的权值 < 顶点j 与其他顶点的权值,则更新lowcost 数组;
         */
        for(j = 1; j < G.numVertexes; j++)
        {
            /* 如果下标为k顶点各边权值小于此前这些顶点未被加入生成树权值 */
            if(lowcost[j]!=0 && G.arc[k][j] < lowcost[j])
            {
                /* 将较小的权值存入lowcost相应位置 */
                lowcost[j] = G.arc[k][j];
                /* 将下标为k的顶点存入adjvex */
                adjvex[j] = k;
            }
        }
    }
    printf("sum = %d\n",sum);
}
4.调用
int main(void)
{
    printf("Hello,最小生成树_Prim算法\n");
    MGraph G;
    CreateMGraph(&G);
    MiniSpanTree_Prim(G);
    return 0;
}
5.输出
Hello,最小生成树_Prim算法
(V0, V1)=10
(V0, V5)=11
(V1, V8)=12
(V8, V2)=8
(V1, V6)=16
(V6, V7)=19
(V7, V4)=7
(V7, V3)=16
sum = 99

三. 克鲁斯卡尔算法

1.算法构造过程
  • 定义parent数组,记录顶点间的连接关系,通过它判断最小生成树是否产生闭环
  • 构建边集数组,根据边表的权值从小到达排序
  • 循环每条边,如果不构成闭环,将此边的结尾顶点放入下标为起点的parent
  • 打印最小生成树路径
2.基础设置
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXEDGE 20
#define MAXVEX 20
#define INFINITYC 65535
typedef int Status;
typedef struct
{
    int arc[MAXVEX][MAXVEX];
    int numVertexes, numEdges;
}MGraph;
/* 对边集数组Edge结构的定义 */
typedef struct
{
    int begin;
    int end;
    int weight;
}Edge ;

/*9.1 创建邻接矩阵*/
void CreateMGraph(MGraph *G)
{
    int i, j;
    
    /* printf("请输入边数和顶点数:"); */
    G->numEdges=15;
    G->numVertexes=9;
    
    for (i = 0; i < G->numVertexes; i++)/* 初始化图 */
    {
        for ( j = 0; j < G->numVertexes; j++)
        {
            if (i==j)
                G->arc[i][j]=0;
            else
                G->arc[i][j] = G->arc[j][i] = INFINITYC;
        }
    }
    G->arc[0][1]=10;
    G->arc[0][5]=11;
    G->arc[1][2]=18;
    G->arc[1][8]=12;
    G->arc[1][6]=16;
    G->arc[2][8]=8;
    G->arc[2][3]=22;
    G->arc[3][8]=21;
    G->arc[3][6]=24;
    G->arc[3][7]=16;
    G->arc[3][4]=20;
    G->arc[4][7]=7;
    G->arc[4][5]=26;
    G->arc[5][6]=17;
    G->arc[6][7]=19;
    for(i = 0; i < G->numVertexes; i++)
    {
        for(j = i; j < G->numVertexes; j++)
        {
            G->arc[j][i] =G->arc[i][j];
        }
    }
}
/* 交换权值以及头和尾 */
void Swapn(Edge *edges,int i, int j)
{
    int tempValue;
    //交换edges[i].begin 和 edges[j].begin 的值
    tempValue = edges[i].begin;
    edges[i].begin = edges[j].begin;
    edges[j].begin = tempValue;
    //交换edges[i].end 和 edges[j].end 的值
    tempValue = edges[i].end;
    edges[i].end = edges[j].end;
    edges[j].end = tempValue;
    //交换edges[i].weight 和 edges[j].weight 的值
    tempValue = edges[i].weight;
    edges[i].weight = edges[j].weight;
    edges[j].weight = tempValue;
}
/* 对权值进行排序 */
void sort(Edge edges[],MGraph *G)
{
    //对权值进行排序(从小到大)
    int i, j;
    for ( i = 0; i < G->numEdges; i++)
    {
        for ( j = i + 1; j < G->numEdges; j++)
        {
            if (edges[i].weight > edges[j].weight)
            {
                Swapn(edges, i, j);
            }
        }
    }
    printf("边集数组根据权值排序之后的为:\n");
    for (i = 0; i < G->numEdges; i++)
    {
        printf("(%d, %d) %d\n", edges[i].begin, edges[i].end, edges[i].weight);
    }
}
/* 查找连线顶点的尾部下标 */
//根据顶点f以及parent 数组,可以找到当前顶点的尾部下标; 帮助我们判断2点之间是否存在闭环问题;
int Find(int *parent, int f)
{
    while ( parent[f] > 0)
    {
        f = parent[f];
    }
    return f;
}
3.核心代码
void MiniSpanTree_Kruskal(MGraph G)
{
    int i, j, n, m;
    int sum = 0;
    int k = 0;
    /* 定义一数组用来判断边与边是否形成环路
     用来记录顶点间的连接关系. 通过它来防止最小生成树产生闭环;*/
    int parent[MAXVEX];
    /* 定义边集数组,edge的结构为begin,end,weight,均为整型 */
    Edge edges[MAXEDGE];
    /*1. 用来构建边集数组*/
    for ( i = 0; i < G.numVertexes-1; i++)
    {
        for (j = i + 1; j < G.numVertexes; j++)
        {
            //如果当前路径权值 != ∞
            if (G.arc[i][j]<INFINITYC)
            {
                //将路径对应的begin,end,weight 存储到edges 边集数组中.
                edges[k].begin = i;
                edges[k].end = j;
                edges[k].weight = G.arc[i][j];
                //边集数组计算器k++;
                k++;
            }
        }
    }
    //2. 对边集数组排序
    sort(edges, &G);
    //3.初始化parent 数组为0. 9个顶点;
    // for (i = 0; i < G.numVertexes; i++)
    for (i = 0; i < MAXVEX; i++)
        parent[i] = 0;
    //4. 计算最小生成树
    printf("打印最小生成树:\n");
    /* 循环每一条边 G.numEdges 有15条边*/
    for (i = 0; i < G.numEdges; i++)
    {
        //获取begin,end 在parent 数组中的信息;
        //如果n = m ,将begin 和 end 连接,就会产生闭合的环.
        n = Find(parent,edges[i].begin);
        m = Find(parent,edges[i].end);
        //printf("n = %d,m = %d\n",n,m);
        /* 假如n与m不等,说明此边没有与现有的生成树形成环路 */
        if (n != m)
        {
            /* 将此边的结尾顶点放入下标为起点的parent中。 */
            /* 表示此顶点已经在生成树集合中 */
            parent[n] = m;
            
            /*打印最小生成树路径*/
            printf("(%d, %d) %d\n", edges[i].begin, edges[i].end, edges[i].weight);
            sum += edges[i].weight;
        }
    }
    printf("sum = %d\n",sum);
}
4. 调用
int main(int argc, const char * argv[]) {
    printf("Hello,最小生成树_Kruskal算法\n");
    MGraph G;
    CreateMGraph(&G);
    MiniSpanTree_Kruskal(G);
    return 0;
}
5. 输出
Hello,最小生成树_Kruskal算法
边集数组根据权值排序之后的为:
(4, 7) 7
(2, 8) 8
(0, 1) 10
(0, 5) 11
(1, 8) 12
(3, 7) 16
(1, 6) 16
(5, 6) 17
(1, 2) 18
(6, 7) 19
(3, 4) 20
(3, 8) 21
(2, 3) 22
(3, 6) 24
(4, 5) 26
打印最小生成树:
(4, 7) 7
(2, 8) 8
(0, 1) 10
(0, 5) 11
(1, 8) 12
(3, 7) 16
(1, 6) 16
(6, 7) 19
sum = 99