Kruskal algorithm-C language explanation

Source: Internet
Author: User

minimum Spanning Tree

Selecting the n-1 edge in a connected graph with n vertices, constituting a minimal connected sub-graph, and minimizing the sum of the weights of the n-1 bars in the connected sub-graph, it is called the smallest spanning tree of the connected net.

For example, for a connected network as shown in G4, you can have multiple spanning trees with different weights combined.

Kruskal Algorithm Introduction

Kruskal (Kruskal) algorithm is used to calculate the minimum spanning tree of weighted connected graphs.

Basic idea : According to the weight of the order from small to large selection n-1 edge, and ensure that this n-1 edge does not constitute a loop.
How to do this: first construct a forest containing only n vertices, then choose the edge from the connected network from small to large in the weight to join the forest, and make no loop in the forest until the forest becomes a tree.

Kruskal algorithm Diagram

Take G4 as an example to demonstrate the Kruskal (assuming that the most niche tree result is saved with the array R).

1th Step : Add edges <E,F> join R.  
     Edge <E,F> has the lowest weight, so it is added to the minimum spanning tree result R. &NBSP
2nd : Add Edge <C,D> join R.  
     after the previous operation, Edge <C,D> has the lowest weight, so it is added to the minimum spanning tree result R. &NBSP
3rd : Add Edge <D,E> join R.  
     after the previous operation, Edge <D,E> has the lowest weight, so it is added to the minimum spanning tree result R. &NBSP
4th : Add Edge <B,F> join R.  
     after the previous operation, Edge <C,E> has the lowest weight, but <C,E> will form the loop with the existing edges, so skip edge <C,E>. Similarly, skip edge <C,F>. Adds edge <B,F> to the minimum spanning tree result R. &NBSP
5th : Add Edge <E,G> join R.  
     after the previous operation, Edge <E,G> has the lowest weight, so it is added to the minimum spanning tree result R. &NBSP
6th : Add Edge <A,B> join R.  
     after the previous operation, Edge <F,G> has the lowest weight, but <F,G> will form the loop with the existing edges, so skip edge <F,G>. Similarly, skip edge <B,C>. Adds edge <A,B> to the minimum spanning tree result R.

At this point, the minimum spanning tree construction is complete! The edges that it includes are:<E,F> <C,D> <D,E> <B,F> <E,G><A,B>.

Kruskal Algorithm Analysis

Based on the basic ideas and practices of the Kruskal algorithm described earlier, we are able to understand that the Kruskal algorithm focuses on the following two issues that need to be addressed:
The problem is sorted by weight size for all edges of the graph.
question two how to determine if a loop is formed when adding edges to the minimum spanning tree.

Problem a good solution, using sorting algorithm to sort.

Problem two is handled by recording the end point of the vertex in the minimum spanning tree, and the end point of the vertex is the largest vertex connected to it in the smallest spanning tree ( which is explained later in the picture). Then each time you need to add an edge to the minimum survival tree, determine whether the end of the two vertices of the edge is coincident, coincident words will constitute a loop. has been explained:

After you add <E,F> <C,D> <D,E> to the minimum spanning tree R, the vertices of these edges all have an end point:

The end of C is f.
(c) the end of D is F.
The end point of E is F.
The end of F is f.

The end point is that all vertices are arranged in order from small to large, and the end point of a vertex is "the largest vertex connected to it". So, next, although <C,E> is the least weighted edge. But the emphasis of C and E is F, that is, they have the same end point, so the <C,E> is added to the minimum spanning tree, which forms a loop. This is how the loop is judged.

code description for the Kruskal algorithm

With the previous algorithm analysis, let's look at the specific code below. Here the "adjacency matrix" to illustrate, the "adjacency table" Implementation of the diagram in the following source code will give the corresponding source code.

1. Basic definition

//Adjacency matrix typedefstruct_graph{Char Vexs[max];//Vertex collectionint vexnum;// vertices int edgnum; // edge number int Matrix[max][max]; // adjacency matrix}graph, *pgraph;// edge structure typedef struct _edgedata{char start; // The beginning of the edge char end; // edge end int weight; // edge weight}edata;         

Graph is the corresponding structure of the adjacency matrix.
Vexs is used to save vertices, Vexnum is the number of vertices, edgnum is the number of edges, and the matrix is a two-dimensional array to hold the matrix information. For example, matrix[i][j]=1 means "vertex I (i.e. vexs[i])" and "Vertex J (i.e. Vexs[j])" are adjacency points; matrix[i][j]=0, they are not adjacency points.
Edata are the structures that correspond to the edges of adjacent matrices.

2. Kruskal algorithm

#include <stdio.h>#include <stdlib.h>#include <malloc.h>#include <String.h>#define MAX 100#define INF-1typedefstructgraph{CharVexs[max];IntVexnum;IntEdgnum;IntMatrix[max][max];} graph,*Pgraph;typedefstructedgedata{CharStartCharEndIntWeight;} EData;Staticint Get_position (Graph g,CharCH) {IntIfor (i=0;i<g.vexnum;i++)if (g.vexs[i]==ChReturnIReturn-1;} graph*Create_graph () {Char vexs[]= {‘A‘,‘B‘,‘C‘,‘D‘,‘E‘,‘F‘,‘G‘};int matrix[][7]={ {0,12,inf,inf,inf,16,14}, {12,0,10,inf,inf,7, INF}, {INF,10,0,3,5,6, INF}, {inf,inf,3,0,4, Inf,inf}, {inf,inf,5,4,0,inf,8}, {16,7,6,inf,2,0,9}, {14,inf,inf,inf,8,9,0}};int vlen=sizeof (VEXS)/sizeof (vexs[0]);IntI,j; Graph *PG;if ((pg= (graph*) malloc (sizeof (Graph)) = =NULL)ReturnNULL; memset (PG,0,sizeof(PG)); pg->vexnum=Vlenfor (i=0;i<pg->vexnum;i++) pg->vexs[i]=Vexs[i];for (i=0;i<pg->vexnum;i++)for (j=0;j<pg->vexnum;j++) pg->matrix[i][j]=MATRIX[I][J];for (i=0;i<pg->vexnum;i++) {for (j=0;j<pg->vexnum;j++) {if (i!=j&&pg->matrix[i][j]!=INF) pg->edgnum++; }} pg->edgnum/=2;ReturnPG;}voidPrint_graph (graph G) {IntI,j; printf"Matrix Graph: \ n");for (i=0;i<g.vexnum;i++) {for (j=0;j<g.vexnum;j++) printf ("%10d", G.matrix[i][j]); printf"\ n"); }}edata*Get_edges (Graph G) {EData *Edges Edges= (edata*) malloc (g.edgnum*sizeof(EData));IntI,j;int index=0;for (i=0;i<g.vexnum;i++) {for (j=i+1;j<g.vexnum;j++) {if (g.matrix[i][j]!=INF) {edges[index].start=G.vexs[i]; Edges[index].end=G.VEXS[J]; edges[index].weight=G.MATRIX[I][J]; index++; } } }Returnedges;}void Sort_edges (EData *edges,IntElen) {Int i,j; for (i=0;i<elen;i++) {for (j=i+1;j<elen;j++) {if (edges[i].weight>edges[j ].weight) {EData tmp=edges[i]; edges[i]=edges[j]; edges[j]=tmp;}} }}int get_end (int vends[],int i) {while (vends[i]!=0) i=vends[i]; return i;} void Kruskal (Graph G) {int i,m,n,p1,p2; int length; int index=0; int vends[max]={0}; EData Rets[max]; EData *edges; Edges=get_edges (G); Sort_edges (Edges,g.edgnum); for (i=0;i<g.edgnum;i++) printf ("%d", edges[i].weight); printf ("\ n"); for (i=0;i<g.edgnum;i++) {p1=get_position (G,edges[i].start); p2=get_position (g,edges[i].end); M=get_end (Vends, p1); N=get_end (VENDS,P2); printf ("m=%d,n=%d", m,n); if (m!=n) {vends[m]=n; rets[index++]=edges[i];}} Free (edges); length=0; for (i=0;i<index;i++) length+=rets[i].weight; printf ("Kruskal =%d\n", length); for (i=0;i<index;i++) printf ("(%c,%c)", rets[i].start,rets[i].end); printf ("\ n");} int main () {Graph *pg; pg=create_graph (); Print_graph (*PG); Kruskal (*PG);} 

Operation Result:

Kruskal algorithm-C language explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.