java实现迪杰斯特拉算法

public class Dijstra {

    private static final int MAXVEX = 9;//顶点数
    private static final int MAXWEIGHT = 65535;
    private int[] shortTablePath = new int[MAXVEX]; //记录v0到某顶点的最短路径和

    //获取一个图的最短路径
    public void shortestDijstra(Graph graph){
        int min;
        int k = 0;//记录下标
        boolean[] isgetPath = new boolean[MAXVEX];  //是否拿到这个顶点的最短路径
        for(int v = 0;v < graph.getVertexSize();v++){
            shortTablePath[v] = graph.getMatrix()[0][v];    //获取v0这一行的权值数组
        }
        shortTablePath[0] = 0;
        isgetPath[0] = true;
        for(int i = 1;i < graph.getVertexSize();i++){
            min = MAXWEIGHT;
            for(int j = 0;j < graph.getVertexSize();j++){
                if(!isgetPath[j] && shortTablePath[j] < min){   //获取有交点的顶点的下标
                    k = j;
                    min = shortTablePath[j];
                }

            }
            isgetPath[k] = true;
            for(int z = 0;z < graph.getVertexSize();z++){
                if(!isgetPath[z] && (min + graph.getMatrix()[k][z] < shortTablePath[z])){
                    shortTablePath[z] = min + graph.getMatrix()[k][z];
                }
            }

        }

        for(int i = 0;i < graph.getVertexSize();i++){
            System.out.println("v0到v" + i + "的最短路径为:" + shortTablePath[i]);
        }
    }


    public static void main(String[] args){
        int[] a0 = new int[]{0,1,5,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT};
        int[] a1 = new int[]{1,0,3,7,5,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT};
        int[] a2 = new int[]{5,3,0,MAXWEIGHT,1,7,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT};
        int[] a3 = new int[]{MAXWEIGHT,7,MAXWEIGHT,0,2,MAXWEIGHT,3,MAXWEIGHT,MAXWEIGHT};
        int[] a4 = new int[]{MAXWEIGHT,5,1,2,0,3,6,9,MAXWEIGHT};
        int[] a5 = new int[]{MAXWEIGHT,MAXWEIGHT,7,MAXWEIGHT,3,0,MAXWEIGHT,5,MAXWEIGHT};
        int[] a6 = new int[]{MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,3,6,MAXWEIGHT,0,2,7};
        int[] a7 = new int[]{MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,9,5,2,0,4};
        int[] a8 = new int[]{MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,7,4,0};
        int[][] arr = new int[9][9];
        arr[0] = a0;
        arr[1] = a1;
        arr[2] = a2;
        arr[3] = a3;
        arr[4] = a4;
        arr[5] = a5;
        arr[6] = a6;
        arr[7] = a7;
        arr[8] = a8;
        Graph graph = new Graph(9);
        graph.setMatrix(arr);
        Dijstra d = new Dijstra();
        d.shortestDijstra(graph);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值