dijstra算法,求源点到各个顶点的最短距离

1:dijstra算法常用语求最短距离,

dijstra每次从未发现节点n[]中,发现距离源点最短的节点m,求出最短节点后,将m添加到已发现节点y[]中,用该节点m进行更新其它未发现节点n[]-m的最短距离。直到发现所有节点

证明:m为什么是距离源点s的最短距离, 

         因为在未发现节点中该节点距离最短,所以不会有从s到n[]-m再到m的距离和小于s到m。

          在已发现节点y[]中,从s到y[]再到m的距离和,如果有小于s到m的距离,那么在求得s>y[i]的最短距离时,就已经用(s>y[i])+(y[i]>m)替换掉s>m的距离了。所以不会存在这种情况

代码:

package com.li.chapter24.mydijstra;

import java.io.InputStream;
import java.util.Scanner;

/**
 * @program: GradleTestUseSubModule
 * @author: Yafei Li
 * @create: 2018-06-28 19:45
 *   自己编写迪杰斯特拉算法  ,解决图论及其应用 1.4节  a到b的最短路问题
 **/
public class MyDijStraAlgorithm {

    public static void main(String[] args){
        MyDijStraAlgorithm dijStraAlgorithm=new MyDijStraAlgorithm();
        int[] minDisArr = dijStraAlgorithm.dijstra(0);  
        for (int i = 0; i < minDisArr.length; i++) {
            System.out.println(minDisArr[i]);
        }
    }
    //vertx输入的源点
    public int[] dijstra(int vertx) {

        int[][] arrWeight=getArrOfGraph();
        int[] arrVertx = arrWeight[vertx];   //其它节点与vertx的距离

        boolean[] isFound = new boolean[arrVertx.length];
        isFound[vertx]=true;

        for (int i = 0; i < arrVertx.length; i++) {  //遍历所有的点
            int mindis=Integer.MAX_VALUE;
            int v=vertx;
            for (int j = 0; j < arrVertx.length; j++) {
                if (!isFound[j]) {
                    if (mindis > arrVertx[j]) {
                        mindis = arrVertx[j];
                        v=j;
                    }
                }
            }

            isFound[v]=true;

            for (int j = 0; j < arrVertx.length; j++) {
                if (!isFound[j]) {
                    if (mindis + arrWeight[v][j] < arrVertx[j]) {  //vertx到v的距离加上v到j的距离
                        arrVertx[j]=mindis + arrWeight[v][j];
                    }
                }
            }
        }
        return arrVertx;

    }


    public int[][] getArrOfGraph() {
        Class clazz = this.getClass();
        InputStream ins = clazz.getResourceAsStream("/data2.txt");
        Scanner scanner = new Scanner(ins);
        int[][] intarr = new int[8][8];
        int row=0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] strarr = line.split(" ");
            for (int i = 0; i < strarr.length; i++) {
                intarr[row][i] = Integer.parseInt(strarr[i]);
            }
            row++;
        }
        return intarr;
    }
}

下面为数据,放到resource下

下面的数据表示,行号,列号代表节点 ,节点为0-7

其中8表示为 第0个节点到第4个节点的距离为8

999代表两个节点之间没有相邻,说明它们的距离无穷大

0 2 999 999 8 999 1 999
2 0 1 999 6 999 999 999
999 1 0 9 4 3 999 999
999 999 9 0 999 6 999 2
8 6 4 999 0 2 7 2
999 999 3 6 2 0 999 4
1 999 999 999 7 999 0 9
999 999 999 2 2 4 9 0

猜你喜欢

转载自www.cnblogs.com/liyafei/p/9241737.html