Prim 算法 Java实现

import java.util.Arrays;

class MST{
    int startVertex;
    int endVertex;
    int length;
    boolean sure = false;

    public MST(int startVertex, int endVertex, int length) {
        this.startVertex = startVertex;
        this.endVertex = endVertex;
        this.length = length;
    }

    @Override
    public String toString() {
        return "(" + startVertex +
                "," + endVertex +
                "," + length +
                ')';
    }
}
public class Main {

    //矩阵阶数
    static int matrixOrder = 6;

    //MST
    static MST[] msts = new MST[matrixOrder - 1];

    //无穷距离
    static int MD = 999;

    //邻接矩阵
    static int[][] arcs = {
            {0,       10,     MD,     MD,    19,     21},
            {10,       0,      5,      6,    MD,     11},
            {MD,       5,      0,      6,    MD,     MD},
            {MD,       6,      6,      0,    18,     14},
            {19,      MD,     MD,     18,     0,     33},
            {21,      11,     MD,      14,    33,     0 }} ;

    static boolean isOver(){
        for(int i = 0; i < msts.length; i++){
            if(!msts[i].sure){
                return false;
            }
        }
        return true;
    }

    static int findMinLengthVertex(){
        int minLength = MD;
        int minIndex = matrixOrder;
        for(int i = 0; i < msts.length; i++){
            if(!msts[i].sure && msts[i].length <= minLength){
                minLength = msts[i].length;
                minIndex = i;
            }
        }
        msts[minIndex].sure = true;
        int minVertexIndex = msts[minIndex].endVertex;
        return minVertexIndex;
    }

    static void prim(){

        //初始化msts
        for(int i = 0; i < msts.length; i++){
            MST mst = new MST(0, i + 1, arcs[0][i+1]);
            msts[i] = mst;
        }

        //算法开始
        while(true){
            if(isOver())
                break;
            int minLengthVertex = findMinLengthVertex();
            for(int i = 0; i < msts.length; i++){
                if(!msts[i].sure && msts[i].length > arcs[minLengthVertex][msts[i].endVertex]){
                    msts[i].startVertex = minLengthVertex;
                    msts[i].length = arcs[minLengthVertex][msts[i].endVertex];
                }
            }
        }

    }

    public static void main(String[] args) {
        prim();
        System.out.println(Arrays.toString(msts));
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值