Minimum spanning tree
Definition: weight spanning tree edges (Consideration) and the smallest tree of
Prim
Prim's algorithm: An algorithm Prim's algorithm, in graph theory, the search for a minimum weight spanning tree in the communication in FIG.
Ps: The algorithm was discovered in 1930 by the Czech mathematician Woyijiehe · Royal Nick (Vojtěch Jarník); and independently discovered by American computer scientist Robert Primm (Robert C. Prim) in 1957; in 1959, Aizi Ge · Dijkstra's algorithm found again. Therefore, in some cases, Prim's algorithm is also known as DJP algorithm, or algorithms Nick Primm Yar - yar Nick algorithms.
Specific ideas algorithm
Info ① create an array [], for all the points to the memory map from the minimum spanning tree
② out a minimum spanning tree vertex added to obtain all vertices in FIG distance from the point of two-dimensional array, and updates the array Info []
③ Info based on the updated array [], to locate the vertex of the minimum spanning tree shortest distance
④ was added to the vertex of the minimum spanning tree, and updates the array Info []:
If no vertex distance is added to the newly added vertex less than the previous vertex to the minimum spanning tree of the distance, the array of Info update
all numbers ⑤ ③④ operation is repeated until the array Info [] is 0, i.e., all the vertices are present in the minimum spanning tree
Diagram
① new array is Info [6]: info [a -1] ( zero-based array), a represents the distance to the vertex of the minimum spanning tree
② is fed to a first vertex 1, to update the array {0,6,1, 5, max, max} (max denotes the maximum value)
③ to find out the minimum value is 1, the corresponding vertex is 3, the minimum spanning tree is added
to identify the most 3 to other distance vertex {1,5,0,5,6 , 4} and the previously drawn {0,6,1,5, max, max} comparison, a small value will be replaced, i.e. shorter path, {0,5,0,5,6 array is updated, 4}
④ minimum value of 4 to find out the corresponding vertex 6, the minimum spanning tree is added
before the operation was repeated to give the corresponding
⑤
⑥
Detailed code
/**
* 构建最小生成树,求得最短路径
* @param sMap 图
* @param first 开始构建树时加入的第一个结点
* @return 最短路径
*/
public int createMinProTree(SimpleMap sMap,int first) {
//构建一个数组,用于存储当前图到其他结点的最小权值
int[] minInfo = new int[sMap.num];
int lenghth = 0;
//初始化数组(从1(数组中索引为0)开始构建)
System.out.println("加入顶点:"+first);
for(int i=0; i<sMap.num; i++) {
//第一列存储最小权值
minInfo[i] = sMap.map[first-1][i];
}
//最小生成树中顶点数
int number = 1;
while(number < 6) {
//遍历当前数组,找到距离最短的路径对应的顶点加入
int minValue = CreateAMap.MAX;
int index = 0;
for(int i=0; i<sMap.num; i++) {
if(minInfo[i] !=0 && minValue > minInfo[i]) {
minValue = minInfo[i];
index = i;
}
}
//将index对应的顶点加入树中,更新树中数据(保持其他顶点到树的距离最短)
System.out.println("加入顶点:"+(index+1));
lenghth += minValue;
minInfo[index] = 0;
for(int i=0; i<sMap.num; i++) {
if(minInfo[i] > sMap.map[index][i]) {
minInfo[i] = sMap.map[index][i];
}
}
number++;
}
return lenghth;
}