Algorithm 1.1 ----- job with Prim minimum spanning tree algorithm

Prim's algorithm

Prim's algorithm (Prim algorithm), an algorithm of the graph theory may search for a minimum weight spanning tree in the communication in FIG.

Algorithm Description

1) Input: a weighted FIG communication, where V is the set of vertices, edge set is E;
2) Initialization: Vnew = {x}, where x is any node (starting point) of the set V, Enew = {. }, is null;
3) repeat the following operation until Vnew = V:
. a selected minimum weight edge <u, v> in the set E, where u is the set Vnew the elements, and v is not Vnew set among and v∈V (if present multiple edges satisfy the aforementioned conditions i.e. having the same weight value item, may select any one of them); B
v is added to the collection Vnew, the <u, v> is added with the collection Enew. ; and
4) output: using a minimum spanning tree to describe the set Vnew and Enew obtained.

Algorithm is illustrated
Here Insert Picture Description
in the figure as an example, if selected as the starting point A is adjacent to A has three sides, and because the minimum weights between AB, B was added so to speak Vnew.
Here Insert Picture Description
In this case A, B Vnew points have been set in, so that five adjacent edge, selecting a minimum value of the neighboring right added Vnew set point.
Here Insert Picture Description
Repeat these steps until all points are elected Vnew, it follows that the minimum spanning tree.
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
Finally obtain the minimum spanning tree
Here Insert Picture Description

algorithm design

Algorithm two parts
1, initialization
2, and find the minimum edge weights update path

void prim(int graph[][MAX], int n)
{
	int Vnew[MAX];     //表示对应Dist的起点
	int Dist[MAX];     //储存已选点和未选点之间的相邻边
	int i, j, min, minid, sum = 0;
	for (i = 2; i <= n; ++i) { //对几个数组进行初始化,因为默认从下标1开始,所以i=2
		Vnew[i] = 1;
		Dist[i] = graph[1][i]; //将顶点1的邻接边读入
	}
	Vnew[1] = 0;
	
	for (i = 2; i <= n; i++) {//查找最小权值边并更新路径
		min = MAXCOST;
		minid = 0;
		for (j = 2; j <= n; j++) {
			if (min > Dist[j] && Dist[j] != 0) { //找出最小边和最小边对应的下标
				min = Dist[j];       
				minid = j;
			}
		}
		printf("%d--->%d : 权值为:%d\n", Vnew[minid], minid, min);
		sum += min;
		Dist[minid] = 0; //minid对应的最路路径为0
		for (j = 2; j <= n; j++)
		{
			if (graph[minid][j] < Dist[j])  //对这一点直达的顶点进行路径更新 //若
			{
				Dist[j] = graph[minid][j];
				Vnew[j] = minid; 
			}
		}
	}
	printf("最小权值和为:%d", sum);
}

Source

https://github.com/Lu-ziyan/-/blob/master/prim.cpp

Original articles published 0 · won praise 0 · Views 6

Guess you like

Origin blog.csdn.net/IIIZONE/article/details/104516413