[Data structure] Minimum spanning tree of graph (Prim algorithm, Kruskal algorithm) (C language)


A spanning tree of a connected graph is a minimal connected subgraph that contains all the vertices in the graph but only n-1 edges enough to form a tree. Among all spanning trees of a connected network, the spanning tree with the smallest sum of side costs is called the minimum cost spanning tree (MST) of the connected network, or the minimum . The minimum cost spanning tree of a connected network can be generated
by using the Prim algorithm and the Kruskal algorithm.

1. Prim algorithm

1.1 Implementation steps

Basic steps :
Assuming that N=(V,{E}) is a connected network, TE is the set of edges in the minimum cost spanning tree.
① Initial U={u0}(u0∈V), TE=empty set;
② Select an edge (u0, v0) with the least cost among all u∈U, v∈VU edges and merge it into the set TE, and merge v0 Enter U;
③ Repeat ② until U=V.
That is, the edge with the smallest weight of a certain vertex is selected each time.
Example :
Prim algorithm steps

1.2 Complete implementation code + comments

# include<stdio.h>
# define MAX_VERTEX_NUM 20								//最多顶点个数
# define INFINITY 32768

/*图的邻接矩阵存储结构*/
typedef char VertexData;
typedef struct {
    
    
	VertexData vertex[MAX_VERTEX_NUM];					//顶点向量
	int arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM];			//邻接矩阵
	int vexnum, arcnum;									//图的顶点数和弧数
}AdjMatrix;

AdjMatrix G;

/*求顶点位置函数*/
int LocateVertex(AdjMatrix* G, VertexData v) {
    
    
	int k;
	for (k = 0; k < G->vexnum; k++) {
    
    
		if (G->vertex[k] == v)
			break;
	}
	return k;
}

/*创建一个无向网*/
void CreateAdjMatrix(AdjMatrix* G) {
    
    
	int i, j, k, weight;
	VertexData v1, v2;
	printf("请输入图的顶点数和弧数:");
	scanf("%d%d", &G->vexnum, &G->arcnum);				//输入图的顶点数和弧数
	for (i = 0; i < G->vexnum; i++) {
    
    					//初始化邻接
		for (j = 0; j < G->vexnum; j++)
			G->arcs[i][j] = INFINITY;
	}
	printf("请输入图的顶点:");
	for (i = 0; i < G->vexnum; i++)
		scanf(" %c", &G->vertex[i]);					//输入图的顶点
	for (k = 0; k < G->arcnum; k++) {
    
    
		printf("请输入第%d条弧的两个顶点和权值:", k + 1);
		scanf(" %c %c %d", &v1, &v2, &weight);			//输入一条弧的两个顶点和权值
		i = LocateVertex(G, v1);
		j = LocateVertex(G, v2);
		G->arcs[i][j] = G->arcs[j][i] = weight;			//建立对称弧
	}
}

/*普利姆算法*/
void Prime(AdjMatrix G) {
    
    
	int min, i, j, k, mincost = 0;
	int adjvex[MAX_VERTEX_NUM];							//保存相关顶点下标
	int lowcost[MAX_VERTEX_NUM];						//保存相关顶点间边的权值
	lowcost[0] = 0;										//初始化第一个权值为0,即v0加入生成树
	adjvex[0] = 0;										//初始化第一个顶点下标为0
	for (i = 1; i < G.vexnum; i++) {
    
    					//循环除下标为0外的全部顶点
		lowcost[i] = G.arcs[0][i];						//将v0顶点与之有边的权值存入数组
		adjvex[i] = 0;									//初始化都为v0下标
	}
	for (i = 1; i < G.vexnum; i++) {
    
    
		min = INFINITY;									//初始化最小权值为无穷大
		j = 1;
		k = 0;
		while (j < G.vexnum) {
    
    
			if (lowcost[j] != 0 && lowcost[j] < min) {
    
    	//如果权值不为0,且权值小于min
				min = lowcost[j];						//则让当前权值成为最小值
				k = j;									//将当前最小值的下标存入k
			}
			j++;
		}
		printf("(%c,%c)", G.vertex[adjvex[k]], G.vertex[k]);	//打印当前顶点边中权值最小边
		lowcost[k] = 0;									//将当前顶点的权值设置为0,表示此顶点已经完成任务
		mincost += min;

		for (j = 1; j < G.vexnum; j++) {
    
    				//循环所有顶点
			if (lowcost[j] != 0 && G.arcs[k][j] < lowcost[j]) {
    
    
				lowcost[j] = G.arcs[k][j];
				adjvex[j] = k;							//将下标为k的顶点存入adjvex
			}
		}
	}
	printf("\n最小代价为:");
	printf("%d\n", mincost);
}

int main() {
    
    
	CreateAdjMatrix(&G);
	printf("\n最小代价生成树为:");
	Prime(G);
	return 0;
}

1.3 Running results

Running result 1

2. Kruskal algorithm

2.1 Implementation steps

Basic steps :
Assuming that N=(V,{E}) is a connected network, arrange the edges in N in order of weight from small to large.
① Treat n vertices as n sets.
② Select edges in order of weight from small to large. The selected edge should satisfy that the two vertices are not in the same vertex set , put the edge into the set of spanning tree edges , and at the same time, the vertices where the two vertices of the edge are located Collection merged.
③ Repeat ② until all vertices are in the same vertex set.
Example :
Kruskal algorithm steps① Arrange the edges to be selected in ascending order of weight, and get: (B,C), 5; (B,D), 6; (C,D), 6; (B,F), 11; (D,F), 14; (A,B), 16; (D,E), 18; (A,E), 19; (A,F), 21; (E,F), 33.
Vertex collection states: {A}, {B}, {C}, {D}, {E}, {F}.
The set of edges of the minimum spanning tree: { }.
② Select an edge with the smallest weight from the edges to be selected: (B,C), 5.
The vertex set state becomes: {A}, {B,C}, {D}, {E}, {F}.
The set of edges of the minimum spanning tree: {(B,C)}.
③ Select an edge with the smallest weight from the edges to be selected: (B,D), 6.
The vertex set state becomes: {A}, {B,C,D}, {E}, {F}.
The set of edges of the minimum spanning tree: {(B,C), (B,D)}.
④ Select an edge with the smallest weight from the edges to be selected: (C, D), 6, because C, D are in the same vertex set {B, C, D}, so give up, and re-select a weight from the edges to be selected Smallest side: (B,F), 11.
The vertex set state becomes: {A}, {B,C,D,F}, {E}.
The set of edges of the minimum spanning tree: {(B,C), (B,D), (B,F)}.
⑤ Select an edge with the smallest weight from the edges to be selected: (D, F), 14, because D, F are in the same vertex set {B, C, D, F}, so give up and re-select an edge from the edges to be selected The edge with the smallest weight: (A,B), 16.
The state of the vertex set becomes: {A,B,C,D,F}, {E}.
The set of edges of the minimum spanning tree: {(B,C), (B,D), (B,F), (A,B)}.
⑥ Select an edge with the smallest weight from the edges to be selected: (D, E), 18.
The vertex set state becomes: {A,B,C,D,F,E}.
The set of edges of the minimum spanning tree: {(B,C), (B,D), (B,F), (A,B), (D,E)}.

So far, all vertices are in the same vertex set {A, B, C, D, F, E}, the algorithm ends, the minimum spanning tree is constructed, and the minimum cost is 5+6+11+16+18=56.

1.2 Complete implementation code + comments

# include<stdio.h>
# define MAX_VERTEX_NUM 20								//最多顶点个数
# define INFINITY 32768

typedef char VertexData;
/*边存储结构*/
typedef struct Edge {
    
    
	int u;
	int v;
	int weight;
}Edge, EdgeVec[MAX_VERTEX_NUM];

/*图存储结构*/
typedef struct EdgeGraph {
    
    
	VertexData vertex[MAX_VERTEX_NUM];	//顶点数组存储顶点信息
	EdgeVec arcs;						//弧数组存储弧信息
	int vexnum, arcnum;					//顶点数,弧数
}EdgeGraph;

/*求顶点位置函数*/
int LocateVertex(EdgeGraph* G, VertexData v) {
    
    
	int k;
	for (k = 0; k < G->vexnum; k++) {
    
    
		if (G->vertex[k] == v)
			break;
	}
	return k;
}

/*创建一个网*/
void Create(EdgeGraph* G) {
    
    
	int i, j, k, weight;
	VertexData v1, v2;
	printf("请输入图的顶点数和弧数:");
	scanf("%d%d", &G->vexnum, &G->arcnum);			//输入图的顶点数和弧数
	for (i = 0; i < G->vexnum; i++)					//初始化弧的权值
		G->arcs[i].weight = INFINITY;
	printf("请输入图的顶点:");
	for (i = 0; i < G->vexnum; i++)
		scanf(" %c", &G->vertex[i]);				//输入图的顶点
	for (k = 0; k < G->arcnum; k++) {
    
    
		printf("请输入第%d条弧的两个顶点和权值:", k + 1);
		scanf(" %c %c %d", &v1, &v2, &weight);		//输入一条弧的两个顶点和权值
		i = LocateVertex(G, v1);
		j = LocateVertex(G, v2);
		G->arcs[k].u = v1;							//建立弧
		G->arcs[k].v = v2;
		G->arcs[k].weight = weight;
	}
}

/*按权值将边从小到大排序*/
void Sort(EdgeGraph* G) {
    
    
	int i, j;
	Edge temp;
	for (i = 0; i < G->arcnum - 1; i++) {
    
    
		for (j = 0; j < G->arcnum - i - 1; j++) {
    
    
			if (G->arcs[j].weight > G->arcs[j + 1].weight) {
    
    
				temp = G->arcs[j];
				G->arcs[j] = G->arcs[j + 1];
				G->arcs[j + 1] = temp;
			}
		}
	}
}

/*克鲁斯卡尔算法*/
void Kruskal(EdgeGraph G) {
    
    
	int i, mincost = 0;
	Sort(&G);										//对边进行按权值排序
	int Vexset[MAX_VERTEX_NUM];						//Vexset数组用于记录顶点集合,下标对应顶点序号,值对应顶点集合序号
	for (i = 0; i < G.vexnum; i++)					//初始化,各顶点均处于单独的顶点集合中
		Vexset[i] = i;
	int v1, v2, vs1, vs2;
	for (int i = 0; i < G.arcnum - 1; i++){
    
    
		v1 = LocateVertex(&G, G.arcs[i].u);			//弧连接的顶点的序号
		v2 = LocateVertex(&G, G.arcs[i].v);
		vs1 = Vexset[v1];							//顶点所在顶点集合
		vs2 = Vexset[v2];
		if (vs1 != vs2){
    
    							//判断两个顶点不在同一顶点集合中
			printf("(%c,%c)", G.arcs[i].u, G.arcs[i].v);
			mincost += G.arcs[i].weight;
			for (int j = 0; j < G.vexnum; j++){
    
    
				if (Vexset[j] == vs2)				//合并顶点集合
					Vexset[j] = vs1;
			}
		}
	}
	printf("\n最小代价为:");
	printf("%d\n", mincost);
}

int main() {
    
    
	EdgeGraph G;
	Create(&G);
	printf("\n最小代价生成树为:");
	Kruskal(G);
	return 0;
}

1.3 Running results

Running result 2
Reference: Geng Guohua "Data Structure - Described in C Language (Second Edition)"

For more data structure content, follow my "Data Structure" column : https://blog.csdn.net/weixin_51450101/category_11514538.html?spm=1001.2014.3001.5482

Guess you like

Origin blog.csdn.net/weixin_51450101/article/details/122989240