Minimum spanning tree algorithm: Java implementation of Kruskal algorithm

Source: Internet
Author: User

Idle, write an algorithm, the minimum spanning tree Kruskal algorithm, relative to prim algorithm to achieve a little bit more trouble

Package trees;  
Import Java.util.HashMap;  
Import Java.util.HashSet;  
Import Java.util.Map;  
Import Java.util.PriorityQueue;  
Import Java.util.Set; /** * Minimum spanning tree Kruskal algorithm, * for a connected weighted graph G, a spanning trees T of G is constructed as follows: * for T He-I-edge E1 of T, we select any edge of G of minimum weight and for the second * edge E2 of T, we select any remain ing edge of G of minimum weight. For the third edge E3 * of T,we Choose any remaining edge of G of minimum weight that dose not produce a cycle with * The previousely selected edges. 
 We continue in this manner until a spanning the is produced. * @author XHW * */public class Kruskalminimumspanningtree {/** * * @param args/Public   
                          static void Main (string[] args) {double graph[][]={{0,1,4,4,5}, {1,0,3,7,5}, {4,3,0,6,double.max_value}, {4,7,6,0,2}, 
                          {5,5,double.max_value,2,0}};  
        Double Tree[][]=minimumspanningtree (graph);  
            if (tree==null) {System.out.println ("no Spanning Tree");  
        System.exit (0);  
        } priorityqueue<edge> Edgelist=generateedgelist (tree);  
        for (Edge e:edgelist) {System.out.println (e);  }/** * Given a weighted adjacency matrix (where i=j, weights 0, if I and J irreducible weights are Double.max), returns a minimum spanning tree, * @param Graph * @return */public static double[][] Minimumspanningtree (double[][] graph) {int  
        Rlength=graph.length;  
        int clength=graph[0].length;  
        Priorityqueue<edge> edgelist;  
        Edgelist=generateedgelist (graph);  
        Double Tree[][]=new Double[rlength][clength]; /** * Initialization Tree */for (int i=0;i<rlength;i++) {for (int j=0;j<clen  
   gth;j++)         {if (i==j) tree[i][j]=0;  
            else Tree[i][j]=double.max_value; The/** * map is used to identify which set a vertex of an edge belongs to, and that the vertex is just beginning to belong to a different set, and when an edge is selected, the two sets are merged, and if the selected edges are within the same set, the There's a loop on the table. * More Highlights: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/*/MAP&LT;INTEGER,SET&L  
        T;integer>> map=new hashmap<integer,set<integer>> ();  
        int edgecount=0;  
                  
                  
            while (Edgecount<rlength-1&&!edgelist.isempty ()) {Edge e=edgelist.poll ();  
            Set<integer> Setu=map.get (E.U);  
            Set<integer> Setv=map.get (E.V);  
            System.out.println (e); The two vertices of the edge do not appear in the other set if (Setu==null&&setv==null) {set<integer> s  
                Et=new hashset<integer> (); Set.add (e.u);  
                Set.add (E.V);  
                Map.put (E.U, set);  
            Map.put (e.v, set);  
                }//has a vertex in the other set, one is not, the set of vertices that is not in is merged into else if (setu==null&&setv!=null) {  
                Map.put (E.U, Setv);  
            Setv.add (E.U);  
                else if (setu!=null&&setv==null) {map.put (e.v, Setu);  
            Setu.add (E.V);  
                }//in separate sets, merging two sets else if (Setu!=setv) {for (int v:setv)  
                          
                {Map.put (V, Setu);  
            } setu.addall (Setv);  
            }//two vertices in the same union, will appear loop, discard else {continue;  
            } tree[e.u][e.v]=e.weight;  
            Tree[e.v][e.u]=e.weight;  
                  
        edgecount++;  
      }        
              
        if (edgecount==rlength-1) return tree;  
    else return null; /** * Generate the order of the edge of the queue * @param graph * @return/private static priorityqueue<ed  
        Ge> generateedgelist (double[][] graph) {priorityqueue<edge> edgelist=new priorityqueue<edge> ();  
        int rlength=graph.length;  
        int clength=graph[0].length;  
                for (int i=0;i<rlength;i++) {for (int j=i+1;j<clength;j++) { if (Graph[i][j]>0&graph[i][j]<double.max_value) {Edge e=new edge (i,j,gr  
                    APH[I][J]);  
                Edgelist.add (e);  
    }} return edgelist;  
    } class Edge implements comparable<edge> {int u;  
    int V;  
          
          
     Double weight;     
    public Edge (int u, int v, double weight) {super ();  
        this.u = u;  
        THIS.V = v;  
    This.weight = weight; @Override public int CompareTo (Edge e) {if (e.weight==weight) return  
        0;  
        else if (weight<e.weight) return-1;  
                  
    else return 1;  
    Public String toString () {return u+ "-" +v+ ":" +weight; }  
          
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.