1 构造图
2 代码
package leaning.graph; /* * 迪杰斯特拉算法求最短路径 * * */ public class Dijkstra { // 表示V0顶点到v8顶点的最短路径的值 private int[] D = new int[9]; // 最短路径 private int[] P = new int[9]; //定义无穷大的数 private int MAX = Integer.MAX_VALUE/2; //定义地图变量 private int[][] map = new int[9][9]; //定义顶点变量 private String[] points = {"v0","v1","v2","v3","v4","v5","v6","v7","v8"}; //初始化地图 public void createMap(){ this.map[0] = new int[]{ 0, 1, 5,MAX,MAX,MAX,MAX,MAX,MAX}; this.map[1] = new int[]{ 1, 0, 3, 7, 5,MAX,MAX,MAX,MAX}; this.map[2] = new int[]{ 5, 3, 0,MAX, 1, 7,MAX,MAX,MAX}; this.map[3] = new int[]{MAX, 7,MAX, 0, 2,MAX, 3,MAX,MAX}; this.map[4] = new int[]{MAX, 5, 1, 2, 0, 3, 6, 9,MAX}; this.map[5] = new int[]{MAX,MAX, 7,MAX, 3, 0,MAX, 5,MAX}; this.map[6] = new int[]{MAX,MAX,MAX, 3, 6,MAX, 0, 2, 7}; this.map[7] = new int[]{MAX,MAX,MAX,MAX, 9, 5, 2, 0, 4}; this.map[8] = new int[]{MAX,MAX,MAX,MAX,MAX,MAX, 7, 4, 0}; } //迪杰斯特拉算法核心 public void dijkstraCore(){ // 1 定义变量 int[] final_ = new int[9] ; // final_[w]=1 表示已经从顶点V0访问了顶点Vw // 2 初始化定义变量 for(int i = 0 ; i < this.points.length ;i++){ final_[i] = 0; P[i] = 0; D[i] = this.map[0][i]; } // 3 V0 -> V0节点 final_[0] = 1; // 4 V0 -> 其它节点 for(int i = 1 ; i < this.points.length ;i++){ int min = this.MAX ; int k = -1; // 4.1 得到D带权数组最小值 for(int j = 0 ; j < this.points.length ; j++ ){ if( final_[j]!=1 && min > D[j]){ min = D[j]; k = j; } } final_[k] = 1; // 4.2 调整 P和D的值 for(int j = 0 ; j < this.points.length ;j++){ if(final_[j]!=1 && ( min + this.map[k][j] ) < D[j] ){ D[j] = min + this.map[k][j]; P[j] = k; } } } } // 输出v0顶点到pointName顶点的最短路径 public void show(String pointName){ int position = getNumber(pointName); System.out.println("V0顶点到顶点"+pointName+"\n最短路径值为: "+this.D[position] + " \n路径为 : " + this.getPath(pointName)); } // 得到v0顶点到pointName顶点的路径 public String getPath(String pointName){ StringBuffer path = new StringBuffer(); path.append(this.invertStr(pointName)); int position = getNumber(pointName); int point = this.P[position]; while(point!=0){ path.append(" >- " + this.invertStr(this.points[point]) ); point = this.P[point]; } String pathString = path.append(" >- " + this.invertStr("v0") ).toString(); return this.invertStr(pathString); } // 得到字符串从后往前顺序的结果 public String invertStr(String str){ StringBuffer result = new StringBuffer(); for(int i = str.length() -1 ; i >= 0 ; i-- ){ result.append(str.charAt(i)); } return result.toString(); } // 得到pointName在points数组中的位置 public int getNumber(String pointName){ int position = -1; for(int i = 0 ; i < this.points.length ;i++ ){ if(this.points[i].endsWith(pointName.replace(" ", ""))){ position = i; break; } } return position; } public static void main(String[] args) { Dijkstra dijkstra = new Dijkstra(); dijkstra.createMap(); dijkstra.dijkstraCore(); dijkstra.show("v8"); } }
4 v0到v8输出结果