普利姆算法--最小生成树

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值