Primmアルゴリズム-最小スパニングツリー

package org.prim;

/**
 * 普利姆算法 -最小生成树
 * A-G分别表示7个村村庄
 * 关于7个村庄修路的问题,使得7个村庄联通,并修路的距离最短
 * @author cjj_1
 * @date 2020-09-08 15:36
 */
public class PrimAlgorithm {
    
    
    public static void main(String[] args) {
    
    
      char[] data = {
    
    'A','B','C','D','E','F','G'};
      //矩阵表示 两两村庄的最小权值
      int[][] edges = new int[][]{
    
    
              {
    
    10000,5,7,10000,10000,10000,2},
              {
    
    5,10000,10000,9,10000,10000,3},
              {
    
    7,10000,10000,10000,8,10000,10000},
              {
    
    10000,9,10000,10000,10000,4,10000},
              {
    
    10000,10000,8,10000,10000,5,4},
              {
    
    10000,10000,10000,4,5,10000,6},
              {
    
    2,3,10000,10000,4,6,10000},
      };
      Mgrapth mgrapth = new Mgrapth(data.length,data,edges);
        MinTree tree = new MinTree(mgrapth);
        tree.createMinTree(tree.mgrapth);

    }
}
class MinTree{
    
    
    Mgrapth mgrapth;
    public  MinTree(Mgrapth mgrapth){
    
    
        this.mgrapth = mgrapth;
    }
    public void  createMinTree(Mgrapth mgrapth){
    
    
        int[] visited = new int[mgrapth.vertexs];
        visited[0] =1;
        int minweight = 10000;
        int h=0;//找到最小生成树的下一个节点
        int h1=0;
        for(int i =1;i<mgrapth.vertexs;i++ ){
    
    
            for (int j =0;j<mgrapth.vertexs;j++){
    
    
                if(visited[j]==1){
    
    
                    for (int n =0;n<mgrapth.vertexs;n++){
    
    
                        if(visited[n]==0 && mgrapth.edges[j][n] < minweight){
    
    
                            h1= j;
                            h = n;
                            minweight = mgrapth.edges[j][n];
                        }
                    }
                }
            }
            visited[h]=1;
            System.out.println("边>>顶点<"+mgrapth.data[h1]+","+mgrapth.data[h]+">,权值:"+minweight);
            minweight = 10000;
        }
    }

}
class Mgrapth{
    
    
    int vertexs;//顶点的个数
    char[] data;//数据
    int[][] edges;//边
    public  Mgrapth(int vertexs,char[] data,int[][] edges){
    
    
        this.data = data;
        this.vertexs=vertexs;
        this.edges = edges;
    }
}

おすすめ

転載: blog.csdn.net/weixin_40128696/article/details/108483854