1:dijstra算法经常使用语求最短距离,java
dijstra每次从未发现节点n[]中,发现距离源点最短的节点m,求出最短节点后,将m添加到已发现节点y[]中,用该节点m进行更新其它未发现节点n[]-m的最短距离。直到发现全部节点算法
证实:m为何是距离源点s的最短距离, this
由于在未发现节点中该节点距离最短,因此不会有从s到n[]-m再到m的距离和小于s到m。spa
在已发现节点y[]中,从s到y[]再到m的距离和,若是有小于s到m的距离,那么在求得s>y[i]的最短距离时,就已经用(s>y[i])+(y[i]>m)替换掉s>m的距离了。因此不会存在这种状况code
代码:blog
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下get
下面的数据表示,行号,列号表明节点 ,节点为0-7it
其中8表示为 第0个节点到第4个节点的距离为8io
999表明两个节点之间没有相邻,说明它们的距离无穷大class
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