Kruskal (Kruskal) algorithm for building minimal spanning tree

**The concept of the minimal spanning tree (Minimum cost Spanning tree):**

Suppose you want to build a highway between N cities, then connecting N cities requires only a n-1 line. At this point, nature will consider how to set up the road network under the most cost-saving premise.

Each of the 2 cities can be set up a highway, corresponding to pay a certain economic cost. Between n cities, you can set up n (n-1)/2 lines, so how do you choose n-1 bars in these possible lines to minimize the overall cost?

**Kruskal (Kruskal) algorithm of the general idea:**

The weights of each edge are sorted from small to large and connected. When connecting, you need to see if the parent node of the two vertices you want to connect to is the same, so that you can connect and update the parent node after the connection.

The figure is:

The first step

Figure 1

Step Two

Figure 2

Step Three

Figure 3

Fourth Step

A->d,c->d,b->c weight is 5, then do not know which one, so to create 2 auxiliary function Is_same,mark_same.

Is_same is used to determine whether the parent node of the 2 points to be connected is the same, if the same indicates that, after the connection, the diagram has a ring, so you can not connect, give up this edge, to find the next edge.

The mark_same is used to update the parent node of the node.

When the node being received is ad, the parent node of the ad is found to be a, so give up;

When the node that gets is a CD, the parent node of the ad is found to be a, so give up;

When the received node is BC, it is found that the parent node of B is itself, the parent node of C is a, the parent node is different, so the connection, and the more parent node

Figure 4

Find half of the matrix, the beginning of each edge, the end point, the weight, put in the edge array

Figure 5

**MixSpanTree.h**

`#ifndef __mixspantree__#define __mixspantree__#include <stdio.h>#include <malloc.h>#include <assert.h>#include <memory.h>#include <stdlib.h>#include <stdbool.h>#define Default_vertex_size 20#define T char//dai biao ding dian de lei xing#define E int#define MAX_COST 0x7FFFFFFFtypedef struct GraphMtx{ int MaxVertices;//zui da ding dian shu liang] int NumVertices;//shi ji ding dian shu liang int NumEdges;//bian de shu lian T* VerticesList;//ding dian list int** Edge;//bian de lian jie xin xi, bu shi 0 jiu shi 1}GraphMtx;typedef struct Edge{ int begin;//边的起点 int end; //边的终点 E cost; //边的权重}Edge;//chu shi hua tuvoid init_graph(GraphMtx* gm);//打印二维数组void show_graph(GraphMtx* gm);//插入顶点void insert_vertex(GraphMtx* gm, T v);//添加顶点间的线void insert_edge(GraphMtx* gm, T v1, T v2, E cost);//用kruskal算法构造最小生成树void minSpanTree_kruskal(GraphMtx* gm);#endif`

**Mixspantree.c**

`#include "mixSpanTree.h" void Init_graph (graphmtx* gm) {gm->maxvertices = default_vertex_size; gm->numedges = gm->numvertices = 0; Kai Pi ding dian de nei cun kong Jian gm->verticeslist = (t*) malloc (sizeof (T) * (gm->maxvertices)); ASSERT (NULL! = gm->verticeslist); Create a two-dimensional array//give an int a level two pointer to an array with 8 int first-level pointers//open up a memory space that can hold gm->maxvertices int-level pointers Gm->edge = (int**) malloc ( sizeof (int*) * (gm->maxvertices)); ASSERT (NULL! = Gm->edge); Open Gm->maxvertices Group, can hold gm->maxvertices int's memory space for (int i = 0; i < gm->maxvertices; ++i) {Gm->edge[i] = (int*) malloc (sizeof (int) * gm->maxvertices); }//Initialize a two-dimensional array//Let the relationship between each vertex be unconnected for (int i = 0; i < gm->maxvertices; ++i) {for (int j = 0; J < Gm->maxver Tices; ++J) {if (i = = j) Gm->edge[i][j] = 0; else gm->edge[i][j] = max_cost; }}}//prints a two-dimensional array of void Show_graph (graphmtx* gm) {printf (""); for (int i = 0; i < gm->numvertices; ++i) {printf ("%c", Gm-> Verticeslist[i]); } printf ("\ n"); for (int i = 0; i < gm->numvertices; ++i) {//At the beginning of the line, print out the name of the vertex printf ("%c:", Gm->verticeslist[i]); for (int j = 0; J < gm->numvertices; ++j) {if (gm->edge[i][j] = = max_cost) {printf ("%c", ' * '); } else{printf ("%d", gm->edge[i][j]); }} printf ("\ n"); } printf ("\ n");} Insert vertex void Insert_vertex (graphmtx* gm, T v) {//Vertex space is full, no more vertices can be inserted if (gm->numvertices >= gm->maxvertices) {retur N } gm->verticeslist[gm->numvertices++] = V;} int Getvertexindex (graphmtx* gm, T v) {for (int i = 0; i < gm->numvertices; ++i) {if (gm->verticeslist[i] = = v) return i; } return-1;} Add line void Insert_edge between vertices (graphmtx* gm, T v1, T v2, E cost) {if (V1 = = v2) return; find subscript Int J = Getvertexindex (GM, v1) of 2 vertices; int k = Getvertexindex (GM, V2); The description finds vertices, and there is no line between the dots if (j! =-1 && k! =-1) {//because there is no direction, so update 2 values gm->edge[j][k] = gm->edge[k][j] = Cost; Number of sides plus a GM->NUMEDGes++; }}//compares the weights of edges, this function is used as a parameter to the Quick sort function. int CMP (const void* A, const void* b) {return ((* (edge*) a). Cost – (* (edge*) b). cost);} Determines whether the parent of the 2 vertices of the parameter is the same bool Is_same (int* father, int begin, int end) {while (Father[begin]! = begin) {begin = Father[begin] ; } while (Father[end]! = end) {end = Father[end]; } return begin = = END;} Find the parent node x of the End node, and then find the parent node y of the Begin node, update the parent node of the X node to yvoid mark_same (int* father, int begin, int end) {while (Father[begin]! = Begin ) {begin = Father[begin]; } while (Father[end]! = end) {end = Father[end]; } Father[end] = begin;} Constructs the minimum spanning tree void Minspantree_kruskal (graphmtx* g) {int n = g->numvertices; with the Kruskal algorithm edge* edge = (edge*) malloc (sizeof (EDGE) * N (n-1)/2); ASSERT (Edge! = NULL); int k = 0; Find half of the matrix, the beginning of each edge, the end point, the weight, placed in the edge array, referring to the above Figure 5 for (int i = 0; i < n; ++i) {for (int j = i; J < N; j + +) {if (g-> EDGE[I][J]! = 0 && g->edge[i][j]! = max_cost) {edge[k].begin = i; Edge[k].end = j; Edge[k].cost = g->edge[i][j]; k++; } }}//Sort by weight (with system function)//First parameter: array to be sorted//second parameter: Number of elements in array//third parameter: Memory space occupied by each array element//Fourth parameter: function pointer, specifying ordered rule qsort (Edge, K, sizeof (Edge), CMP); Initialize the parent node of each node so that the parent node of each node is itself int *father = (int*) malloc (sizeof (int) * n); ASSERT (NULL! = father); for (int i = 0; i < n; ++i) {father[i] = i; } for (int i = 0; i < n; ++i) {//Determine if the parent node of 2 nodes is the same, connect if (!is_same (father, Edge[i].begin, edge[i].end)) {pri NTF ("%c->%c:%d\n", G->verticeslist[edge[i].begin],g->verticeslist[edge[i].end], edge[i].cost); After the connection, find the node end of the parent node X, and then find the node begin the parent node Y, the parent node x is updated to Y Mark_same (father, Edge[i].begin, edge[i].end); } }}`

**Mixspantreemain.c**

`#include "mixSpanTree.h"int main(){ GraphMtx gm; //初始化图 init_graph(&gm); //插入顶点 insert_vertex(&gm, ‘A‘); insert_vertex(&gm, ‘B‘); insert_vertex(&gm, ‘C‘); insert_vertex(&gm, ‘D‘); insert_vertex(&gm, ‘E‘); insert_vertex(&gm, ‘F‘); //添加连线 insert_edge(&gm, ‘A‘, ‘B‘, 6); insert_edge(&gm, ‘A‘, ‘D‘, 5); insert_edge(&gm, ‘A‘, ‘C‘, 1); insert_edge(&gm, ‘B‘, ‘E‘, 3); insert_edge(&gm, ‘B‘, ‘C‘, 5); insert_edge(&gm, ‘C‘, ‘E‘, 6); insert_edge(&gm, ‘C‘, ‘D‘, 5); insert_edge(&gm, ‘C‘, ‘F‘, 4); insert_edge(&gm, ‘F‘, ‘E‘, 6); insert_edge(&gm, ‘D‘, ‘F‘, 2); //打印图 show_graph(&gm); //kruskal minSpanTree_kruskal(&gm);}`

Full code

Compilation method: Gcc-g mixspantree.c mixspantreemain.c

Kruskal (Kruskal) algorithm for building minimal spanning tree