Minimum Spanning Tree --- Prim algorithm and Kruskal algorithm, --- primkruskal
Prim algorithm
1. Overview
Prim algorithm(Prim algorithm), an algorithm in graph theory that can search for the minimum spanning tree in a weighted connected graph. That is, in the tree composed of edge subsets searched by this algorithm, not only all vertices in a connected graph (Vertex (graph theory) are included )), the sum of the weights of all edges is also the smallest. The algorithm was found in October 1930 by Czech mathematician Vojt ~ch jarník. In 1957, it was found by American computer scientist Robert prham (English: Robert C. prim) Independent discovery; in 1959, izger Dickus again discovered this algorithm. Therefore, in some cases, the prim algorithm is also called the DJP algorithm, the yenick algorithm, or the PrM-yenick algorithm.
2. Simple Algorithm Description
1) input: A Weighted Connected Graph with vertex set V and edge set E;
2). Initialization: Vnew = {x}. x indicates any node (starting point) and Enew = {} In set V. It is null;
3) Repeat the following operations until Vnew = V:
A. select the edge with the smallest weight value <u, v> in set E, where u is the element in the Set Vnew, and v is not in the Vnew set, and v in V (if there are multiple edges that meet the preceding conditions, that is, they have the same weight value, you can select any one of them );
B. Add v to the set Vnew and <u, v> edge to the set Enew;
4). Output: use the set Vnew and Enew to describe the obtained Minimum Spanning Tree.
Example:
The following figure shows the legend of the algorithm:
| Legend |
Description |
Not optional |
Optional |
Selected (Vnew) |
|
|
This is the original Weighted Connected Graph. The number on one side of each edge indicates its weight. |
- |
- |
- |
|
|
VertexDIs selected as the starting point. VertexA,B,EAndFThrough a single edge andD.AYesdistanceDThe nearest vertex, soAAnd corresponding edgeADHighlighted. |
C, G |
A, B, E, F |
D |
|
|
The next vertex is the distance.DOrAThe nearest vertex.BDistanceDIs 9, distanceA7,E15,FIs 6. Therefore,FDistanceDOrARecentlyFAnd corresponding edgeDFHighlighted. |
C, G |
B, E, F |
A, D |
|
The algorithm continues to repeat the preceding steps. DistanceA7 verticesBHighlighted. |
C |
B, E, G |
A, D, F |
|
|
In the current situation, you canC,EAndG.CDistanceB8,EDistanceB7,GDistanceFIs 11.ERecentlyEAnd corresponding edgeBEHighlighted. |
None |
C, E, G |
A, D, F, B |
|
|
Here, the available vertex is onlyCAndG.CDistanceE5,GDistanceEIs 9, so selectCAnd EdgeECHighlighted together. |
None |
C, G |
A, D, F, B, E |
|
|
VertexGIs the only remaining vertex.FIs 11, distanceE9,ERecent, so highlightedGAnd corresponding edgeEG. |
None |
G |
A, D, F, B, E, C |
|
|
Now, all vertices have been selected, and the green part of the graph is the minimum spanning tree of the connected graph. In this example, the sum of the Minimum Spanning Tree weights is 39. |
None |
None |
A, D, F, B, E, C, G |
3. Simple Proof of prim algorithm
Proof Method: Assume that prim does not generate the Minimum Spanning Tree.
1) set the tree generated by prim to G0
2) Assume that there is Gmin so that cost (Gmin) <cost (G0) exists in Gmin that <u, v> does not belong to G0
3) add <u, v> to G0 to obtain a ring, and <u, v> is not the longest side of the ring (this is because <u, v> ε Gmin)
4). This conflicts with the shortest edge generated by prim each time.
5). Therefore, the hypothesis is not true and the proposition is proved.
Kruskal Algorithm
1. Overview
Kruskal AlgorithmThis is an algorithm used to find the smallest spanning tree. It was published by Joseph Kruskal in 1956. The Prim algorithm and Boruvka algorithm are used to solve the same problem. All three algorithms are greedy algorithms. Unlike the Boruvka algorithm, the Kruskal algorithm is also effective when an edge with the same weight value exists in the graph.
2. Simple Algorithm Description
1) Remember that the Graph has v vertices and e edges.
2) Create a New Graph Graphnew. In Graphnew, the same e vertex in the source image has no edges.
3) Sort all e edges in the source Graph by weight from small to large.
4). Loop: traverse each edge from the edge with the smallest weight until all nodes in the Graph are in the same connected component.
If the two nodes connected by this edge are not in the same connected component in graph Graphnew
Add this edge to graph Graphnew
Example:
Legend description:
First, we have a Graph with several vertices and edges.
Sort the length of all edges and use the sorting result as the basis for edge selection. The greedy algorithm is embodied here again. Sort resources and select the local optimal resources. After sorting, we first select edge AD. In this way, our graph becomes the right graph.
Search for the remaining changes. We found CE. The weight here is also 5
And so on, we found 6, 7, 7, DF, AB, and BE.
Next we will continue to select, although the side with the current length of 8 is the smallest unselected side. But now they are connected (for BC, CE and EB can be connected, similar EF can be connected through EB, BA, AD, DF ). Therefore, you do not need to select them. Similar BD has been connected (the connection line here is marked in red ).
At last, the EG and FG are left. Of course we chose EG. The final success figure is right:
3. Simple Proof of the Kruskal Algorithm
Sums up the vertex number n of the graph to prove that the Kruskal algorithm is applicable to any n-level graph.
Induction basics:
N = 1, obviously the minimum spanning tree can be found.
Induction process:
Assuming that the Kruskal algorithm is applicable to a n ≤ k-level graph, in k + 1-level graph G, we merge the two endpoints a and B of the shortest edge, that is to say, combine u and v into a vertex v, and connect all the edges connected to u and v to v. In this way, a k-order graph G' (u, the merge of v is k + 1 with only one edge). You can use the Kruskal algorithm to obtain g'minimum Spanning Tree t.
We prove that t' + {<u, v>} is the minimum spanning tree of G.
Using the reverse identification method, if t' + {<u, v >} is not the Minimum Spanning Tree, the Minimum Spanning Tree is T, that is, W (T) <W (T '+ {<u, v> }). Obviously T should contain <u, v>. Otherwise, you can add <u, v> to T to form a ring and delete any existing edge on the ring, build a tree with smaller weights. T-{<u, v >}is the generator tree of G. So W (T-{<u, v >}) <= W (t'), that is, W (T) <= W (t') + W (<u, v>) = W (t' + {<u, v>. Therefore, if it is not true, T' + {<u, v>} is the minimum generation tree of G, and the Kruskal algorithm is also applicable to k + level 1 graphs.
Based on mathematical induction, the Kruskal algorithm proves.
The following uses a java program to demonstrate the Prim algorithm:
The Code is as follows:
Package com. itheima. primer; import java. util. arrayList; import java. util. list; import java. util. vertex;/*** Minimum Spanning Tree (Prim algorithm) * @ author zhangming * @ date 2016/04/20 */public class MinTreePrimer {private static List <Vertex> visitedVertexs, leftedVertexs; // The private static List of the node set in the node set and the remaining set V added to the set U <Edge> searchEdges; // initialize the public static void initGraph (Graph g) {visitedVertexs = new ArrayList <Vertex> (); leftedVertexs = new ArrayList <Vertex> (); searchEdges = new ArrayList <Edge> (); vertex SC = new vertex (System. in); System. out. print ("Number of input vertices:"); int vertexNumber = SC. nextInt (); System. out. print ("Enter the number of edges:"); int edgeNumber = SC. nextInt (); String [] allVertex = new String [vertexNumber]; String [] allEdge = new String [edgeNumber]; System. out. println ("================================ "); system. out. println ("enter each vertex:"); vertex = new vertex (System. in); for (int I = 0; I <vertexNumber; I ++) {System. out. print ("vertex" + (I + 1) + ":"); allVertex [I] = vertex. nextLine ();} System. out. println ("================================ "); for (int I = 0; I <edgeNumber; I ++) {System. out. print ("vertex name and weight W (for example, a B 7) in the input edge (Vi, Vj):"); allEdge [I] = vertex. nextLine ();} g. vertex = new Vertex [allVertex. length]; g. edge = new Edge [allEdge. length]; g. minWeight = 0; for (int I = 0; I <allVertex. length; I ++) {g. vertex [I] = new Vertex (); g. vertex [I]. vName = allVertex [I]; leftedVertexs. add (g. vertex [I]); // initialize the remaining vertex set} for (int I = 0; I <allEdge. length; I ++) {g. edge [I] = new Edge (); g. edge [I]. startVertex = new Vertex (); g. edge [I]. endVertex = new Vertex (); String edgeInfo [] = allEdge [I]. split (""); g. edge [I]. startVertex. vName = edgeInfo [0]; g. edge [I]. endVertex. vName = edgeInfo [1]; g. edge [I]. weight = Integer. parseInt (edgeInfo [2]);} public static void onChangeVertex (Vertex vertex) {visitedVertexs. add (vertex); // add the initial node as the default Start Node leftedVertexs. remove (vertex);} public static Vertex findOneVertex (Graph g) {int minValue = Integer. MAX_VALUE; Vertex findVertex = new Vertex (); Edge findEdge = new Edge (); for (int I = 0; I <visitedVertexs. size (); I ++) {for (int j = 0; j <leftedVertexs. size (); j ++) {Vertex v1 = visitedVertexs. get (I); Vertex v2 = leftedVertexs. get (j); // obtain the names of two vertices for (int k = 0; k <g. edge. length; k ++) {String startName = g. edge [k]. startVertex. vName; String endName = g. edge [k]. endVertex. vName; if (v1.vName. equals (startName) & v2.vName. equals (endName ))
| (V1.vName. equals (endName) & v2.vName. equals (startName) {if (g. edge [k]. weight <minValue) {findEdge = g. edge [k]; minValue = g. edge [k]. weight; if (leftedVertexs. contains (v1) {// call the equals method of the object to compare objects. You must override the equals method findVertex = v1;} else if (leftedVertexs. contains (v2) {findVertex = v2 ;}}}} g. minWeight + = minValue; searchEdges. add (findEdge); return findVertex;} public static void prim (Graph g) {while (leftedVertexs. size ()> 0) {// ends the cycle until the remaining node set is null Vertex findVertex = findOneVertex (g); onChangeVertex (findVertex);} System. out. print ("\ n edge contained in the shortest path:"); for (int I = 0; I <searchEdges. size (); I ++) {System. out. print ("(" + searchEdges. get (I ). startVertex. vName + "," + searchEdges. get (I ). endVertex. vName + ")" + "");} System. out. println ("\ n Shortest Path Length:" + g. minWeight);} public static void main (String [] args) {Graph g = new Graph (); initGraph (g); onChangeVertex (g. vertex [0]); prim (g) ;}/ *** Vertex class Vertex */class vertex {String vName; // Vertex name @ Override public boolean equals (Object obj) {if (obj instanceof Vertex) {vertex Vertex = (Vertex) obj; return this. vName. equals (vertex. vName);} return super. equals (obj) ;}/ *** Edge class Edge */class Edge {Vertex startVertex; Vertex endVertex; int weight ;} /*** Graph Storage Structure */class Graph {Vertex [] vertex; // Vertex set Edge [] edge; // Edge set int minWeight; // Shortest Path}
Running result: