1.場景:
1.1.對於最短路徑,我們通常考慮使用貪心算法,動態規划,或者dfs,但是dfs存在的問題是隨着節點數量的增加,算法時間復雜度太高,所以,對於節點數過多的圖中,最短路徑的計算,我們考慮使用貪心算法和動態規划,下面是給出的問題:求出1到6最短的路徑,

2.代碼實現:
djstl.java
package com.hfm.util; import java.util.Arrays; public class djstl { public static void main(String[] args) { int i = 7,j = i; int map[][] = new int[i][j]; initMap(map,i,j); int dest[] = new int[i]; for (int k = 0; k < dest.length; k++) { dest[k] = Integer.MAX_VALUE; } System.out.println(Arrays.toString(dest)); search(dest,map,i,j); int loc = 0; for (int ds : dest) { System.out.println("點1到點"+loc+"距離:"+ds); loc ++; } } public static void initMap(int map[][],int i,int j){ for (int k = 0; k < i; k++) { for (int l = 0; l <j ; l++) { if(k == l) map[k][l] = 0; else map[k][l] = Integer.MIN_VALUE; } } map[1][3] = 10; map[1][5] = 30; map[1][6] = 100; map[2][3] = 5; map[3][4] = 50; map[4][5] = 20; map[4][6] = 10; map[5][6] = 60; } public static void search(int dest[],int map[][],int i,int j){ int cur = 1; boolean mark[] = new boolean[dest.length]; boolean visited = false; while (cur <dest.length){ int min = Integer.MAX_VALUE,loc=1; for (int k = 0; k < dest.length; k++) { if(dest[k]<min && !mark[k]){ loc = k; min = dest[k]; } } for (int l = 1; l <j ; l++) { if(loc == 1 && map[loc][l] != Integer.MIN_VALUE && !visited){ dest[l] = map[loc][l]; visited = true; }else if(l != loc && map[loc][l] != Integer.MIN_VALUE && dest[loc] + map[loc][l]< dest[l]){ dest[l] = dest[loc] + map[loc][l]; } } mark[loc] = true; cur ++; } } }
3.使用場景:
求最短路徑,如果節點數量多,則考慮使用鄰接表替換代碼中的鄰接矩陣

