克鲁斯卡尔算法举例

花了很长的时间,把克鲁斯卡尔算法给研究明白到了“入门”的级别,通过举例的方式来说明。

在这里插入图片描述
代码中的图内容取自上图



#include<stdio.h>

 

#define MAX 100

 

int line[MAX];

int lineNum;

 

struct Edge

{

    int begin;

    int end;

    int weight;

};

 

struct Graph

{

    struct Edge edge[MAX];

    int edgeNum;

}graph;

 

void init()

{

    graph.edge[0].begin = 0;

    graph.edge[0].end = 2;

    graph.edge[0].weight = 1;

    graph.edge[1].begin = 3;

    graph.edge[1].end = 5;

    graph.edge[1].weight = 2;

    graph.edge[2].begin = 1;

    graph.edge[2].end = 4;

    graph.edge[2].weight = 3;

    graph.edge[3].begin = 2;

    graph.edge[3].end = 5;

    graph.edge[3].weight = 4;

    graph.edge[4].begin = 0;

    graph.edge[4].end = 3;

    graph.edge[4].weight = 5;

    graph.edge[5].begin = 1;

    graph.edge[5].end = 2;

    graph.edge[5].weight = 5;

    graph.edge[6].begin = 2;

    graph.edge[6].end = 3;

    graph.edge[6].weight = 5;

    graph.edge[7].begin = 0;

    graph.edge[7].end = 1;

    graph.edge[7].weight = 6;

    graph.edge[8].begin = 4;

    graph.edge[8].end = 5;

    graph.edge[8].weight = 6;

    graph.edgeNum = 9;

    lineNum = graph.edgeNum;

    for (int i = 0; i < lineNum; i++)

    {

         line[i] = 0;

    }

}

 

int getEnd(int a)

{

    for (;line[a] != 0;)

    {

         a = line[a];

    }

    return a;

}

 

int main()

{

    init();

    for (int m, n, i = 0, s = 0; i < graph.edgeNum; i++)

    {

         m = getEnd(graph.edge[i].begin);

         n = getEnd(graph.edge[i].end);

         if (m != n)

         {

             line[m] = n;

             printf("第%d条,起点和终点为:%d到%d,权值:%d\n", ++s,
graph.edge[i].begin, graph.edge[i].end, graph.edge[i].weight);

         }

    }

    getchar();

    return 0;

}


结果图片显示一下:
在这里插入图片描述

克鲁斯卡尔算法算法在我所学的《数据结构》里面主要面对的是无向网。
这里之前我想:就这样写成单向网的话,会不会出现遗漏的情况?
后面经过电脑测试和草稿验算,都是没有错误的,我也不知道是为什么,就是这么神奇!哈哈。
这次所研究出的内容是从该网址出来的,写的很不错:https://blog.csdn.net/junya_zhang/article/details/83584592

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值