In an edge-weighted graph, the spanning tree with the smallest sum of weights is called the minimum spanning tree. There are two algorithms for constructing the minimum spanning tree, namely the prim algorithm and the Kruskal algorithm. In the edge-weighted graph, as shown in:
In the above weighting diagram, you can see the weights of the vertex numbers and the adjacent edges between the vertices of the graph, to build the smallest spanning tree since. The result should be as follows:
This minimizes the sum of the weights of the smallest spanning tree that is built, which is 17
In the construction of the minimum spanning tree, there are generally two algorithms, the prim algorithm and the Kruskal algorithm
In the prim algorithm, the minimum spanning-tree algorithm is established by adding the minimum adjacency edge method. First, construct a 0 graph, select an initial vertex to add to the new collection, and then extract a vertex in the original vertex collection, make the resulting edge a minimum weight, then add the pen edge to the graph, and add the extracted vertices to the new collection, repeating the process, knowing that the new collection equals the original collection.
The code is as follows:
package minimum Spanning tree;/* * minimum spanning tree prim algorithm, adding minimal adjacency edge to generate minimum spanning tree. * first constructs a 0 diagram, selects an initial point to join in the collection, * and then extracts a vertex from the set of the original vertex, * the selection criterion is the minimum weight of the resulting tree, * Gradually build a minimum spanning tree */public class prim { /** * @author Liu Yanbing * @date 2015-02-13 20:23 */ /* * m: defined as an unreachable distance * weight: adjacency matrix table, Weight representation weight * vernum: Number of vertices * lowerw: minimum weight to new collection * edge: Stores the edge * checked of the new collection: Determines whether the vertex is extracted from the collection */ static Int m=integer.max_value; static int[][] weight={ {0, 0, 0, 0, 0, 0}, {0, m, 6, 9, 5, 13}, {0, 6, m, 6,7,8}, {0, 9,6,m,9,3}, {0, 5,7,9,m,3}, {0, 13,8,3,3,m} }; static int vernum=weight.length; static int [] Lowerw=new int[vernum]; static int []edge=new int[vernum]; static boolean []checked=new boolean[vernum]; public void prim (int n,int [][]w) { checked[1]=true; //extraction of the first vertex for (int i=1;i<=n;i++) { //Initialize Vertex collection lowerw[i]=w[1][i]; edge[i]=1; checked[i]= False; } for (int i=1;i<=n;i++) { int min= Integer.max_value; int j=1; for (int k=2;k<=n;k++) { //determines whether to extract the vertex if (lowerw[k]<min&& (!checked[ K])) { min=lowerw[k]; j=k; } } if (i<n) //avoid the case of outputting the first vertex to the first vertex system.out.println (j+ "--" +edge[j]); checked[j]=true; // Joins the vertex to the new collection for (int k=2;k<=n;k++) { //based on the newly added vertices, the minimum weights if ((W[j][k]<lowerw[k]) && (!checked[k]) are obtained { lowerW[k]=weight[j][k]; edge[k]=j; } } } } public static void main (String[ ] args) { // todo auto-generated method stub prim p= New prim (); p.prim (VernuM-1,weight); }}
The test results are as follows:
In the Kruskal algorithm, the minimum spanning tree is gradually established based on the weights of the edges in an incremental manner. Each vertex of the weighting graph is treated as a forest, then the weights of each adjacent edge in the graph are arranged in ascending order, the edges with the least weight are extracted from the arranged adjacency edge table, the starting and ending vertices of the edge are written, the connection vertices are the forest tree, and then the adjacency edge of the starting end vertex is read. Prioritize adjacent edges with small weights, and continue to connect vertices to make the forest a tree. The requirement to add adjacent edges is that the adjacency edges added to the diagram do not constitute loops. This is repeated until the n-1 edge has been added.
The code is as follows:
package minimum Spanning Tree;import java.util.arraylist;import java.util.scanner;/* * Minimum spanning Tree Kruskal algorithm: First, each vertex as a forest, ascending comparison of the vertex adjacent edge, * each take the minimum weight of the adjacent edge, the adjacent edge connected vertex and the original vertex form a tree, and then find * next vertex, Continue to compare the neighboring edge weights in ascending order, take the minimum weight of the constituent tree ... * * the class uses an edge class to form an adjacent edge, including the starting vertex and ending vertex of the adjacent edge, and the weight value. * use edge to create objects, input object information, according to the weight of the object to compare, matching the conditions of the object to join * to the list, and finally output the smallest spanning tree in the order of the list. */public class kruskal { /** * @author Liu Yanbing * @ Date 2015-02-13 20:23 */ /* * max: Defines the maximum value of the vertex array * edge: List edge, storage constructed edge object * target: Linked list trget, storing the Edge object * parent that results in the final result: Array of storage vertex information * n: Top Count */ int max=100; arraylist<edge>edge=new ArrayList<Edge> (); arraylist<edge>target=new arraylist<edge> (); int[] parent=new int[max]; float themax=float.max_value; int&nbSp;n; public void init () { /** * p: start vertex * q: End vertex * w: Weight of Edge * n: number of vertices */ Scanner scan =new scanner (system.in); int p,q; double w; system.out.println ("Please enter the number of nodes:"); n=scan.nextint (); system.out.println ("according to ' A,B,C ' The format of the input edge and edge information, ABC represents the beginning vertex of the edge, the end vertex, the weight (input -1 -1 -1 end input): "); while (true) { p= Scan.nextint (); q=scan.nextint (); w=scan.nextdouble (); if (P <0| | q<0| | w<0) Break; edge e=new edge (); e.start=p; e.end =q; e.weight=w; edge.add (e); } for (int i=1;i<= N;++i) { //array of initialized edges parent[i]=i; } } /* * object merging, the end edge of the previous object as the starting edge of the next object */ public void union (int j,int k) { for (int i=1;i<=n;++i) { if (parent[i]==j ) parent[i]=k; } } public void kruskal () { int i=0; //Vertex while (i<n-1&&edge.size () >0) { //If there is only one edge or no edge jumping double min=double.max_value; edge temp=null ; for (Int j=0;j<edge.size (); ++j) { //traverse graph edge tt=edge.get (j); if (tt.weight<min) { //If two vertices have a value, that is, connect min=tt.weight; temp=tt; } } //Construct a tree Int jj=parent[temp.start]; int kk=parent[temp.end]; if (JJ!=KK) { ++i; //end as the start of the next edge, looking for the next edge target.add (temp); //the found edge into the target collection union (JJ,KK); } edge.remove (temp); //Remove the temporary edge } system.out.println (" The path to the minimum spanning tree is: "); for (Int k=0;k<target.size (); ++k) { //output minimum spanning tree edge e=target.get (k); system.out.println (e.start+ "-and" +e.end); } } public static void main (String[] args) { // TODO Auto-generated method stub kruskal kr=new kruskal (); kr.init (); kr.kruskal (); }}/* * start: Start vertex * end: End vertex * weight: Weighted value */class Edge{ public int start; public int end; Public double weight;}
The debug results are as follows:
Java Prim algorithm and Kruskal algorithm for minimal spanning tree