使用Dijkstra迪杰斯特拉算法获得单源最短路径

来源:互联网 发布:王震对新疆的功过知乎 编辑:程序博客网 时间:2024/04/26 13:25

在连通图当中 ,常常出现求出某一个点到其他各个点的最短路径问题

Dijkstra迪杰斯特拉算法就是用来解决这种问题的一种方法

简单的来说,Dijkstra算法就是不断的去使用贪心策略来解决问题

以起始点为中心向外层层扩展,直到扩展到终点为止。Dijkstra算法能得出最短路径的最优解,但由于它遍历计算的节点很多,所以效率并不高。

现有如下的例题:



/**
 * 1.sure[i] means if the path from the start point to i point is sured

sure数组表示从起点到i点之间的最短路径是否已经确定
 * 2.distance[i] means the shortest path from start point to i point currently

distance表示当前这一轮循环结束到各个点最短路径状况

 * 3.piro[i] means i point's previous point

piro数组表示到i点最短路径上的i点的上一个节点的编号

* 4.supposed that the max length of path will not over 200

假设最长的路径也不会超过200,即是200表示路径不可达为无穷大量

 * @author zero
 *
 */

/** * 1.sure[i] means if the path from the start point to i point is sured * 2.distance[i] means the shortest path from start point to i point currently * 3.piro[i] means i point's previous point * 4.supposed that the max length of path will not over 200 * @author zero * */public class Dijkstra {private int[] sure = {0, 0, 0, 0, 0};private int[] distance = {200, 200, 200, 200, 200};private int[] piro = {-1, -1, -1, -1, -1};private int[][] Matrix = {{0, 10, 200, 30, 100},{200, 0, 50, 200, 200},{200, 200, 0, 200, 10},{200, 200, 20, 0, 60},{200, 200, 200, 200, 0}};public void setInitPoint(int index) {sure[index-1] = 1;distance[index-1] = 0;piro[index-1] = 1;dijkstra(index);}public void dijkstra(int index) {int minWeight = 200;int minWeightIndex = -1;for(int i=0; i<5; i++) {if(((Matrix[index-1][i] + distance[index-1]) < distance[i]) && (sure[i] == 0)) {distance[i] = Matrix[index-1][i] + distance[index-1];piro[i] = index;if(minWeight > distance[i]) {minWeight = distance[i];minWeightIndex = i;}}}for(int i=0; i<5; i++) {if((distance[i] < minWeight) && (sure[i] == 0)) {minWeight = distance[i];minWeightIndex = i;}}if(minWeightIndex != -1) {sure[minWeightIndex] = 1;if(!allSure()) {outResult();System.out.println("end this turn");System.out.println("the next start point is :" + (minWeightIndex+1));dijkstra(minWeightIndex+1);}}}public Boolean allSure() {Boolean result = true;for(int i=0; i<sure.length; i++) {if(sure[i] == 0) {result = false;}}return result;}public void outResult() {System.out.print("distance[] : "); for(int length : distance) {System.out.print(length + " ");}System.out.print("\npiro[] : ");for(int index : piro) {System.out.print(index + " ");}System.out.println("");}public static void main(String[] args) {Dijkstra dijkstra = new Dijkstra();dijkstra.setInitPoint(1);dijkstra.outResult();}}

输出的结果为:

distance[] : 0 10 200 30 100
piro[] : 1 1 -1 1 1
end this turn
the next start point is :2
distance[] : 0 10 60 30 100
piro[] : 1 1 2 1 1
end this turn
the next start point is :4
distance[] : 0 10 50 30 90
piro[] : 1 1 4 1 4
end this turn
the next start point is :3
distance[] : 0 10 50 30 60
piro[] : 1 1 4 1 3





0 0
原创粉丝点击