JAVA實現最短距離算法之迪傑斯特拉算法

最短路徑問題是圖論研究中的一個經典的算法問題,旨在尋找圖中兩個節點之間的最短路徑,最經常使用的算法有Dijkstra算法、SPFA算法\Bellman-Ford算法、Floyd算法\Floyd-Warshall算法、Johnson算法等,這篇博客將重點介紹Dijkstra算法。java

 

迪傑斯特拉算法node

      迪傑斯特拉算法是由荷蘭計算機科學家狄克斯特拉於1959 年提出的,所以又叫狄克斯特拉算法。是從一個頂點到其他各頂點的最短路徑算法,解決的是有向圖中最短路徑問題。迪傑斯特拉算法主要特色是以起始點爲中心向外層層擴展,直到擴展到終點爲止。具體的計算規則咱們能夠經過下圖進行查看。算法

img

      經過這幅圖(若是圖片沒法正確顯示,請經過百度百科查看)咱們能夠簡單的理解迪傑斯特拉算法算法的基礎思路,下面咱們就經過Java來實現這個算法。數組

 

先給出一個無向圖數據結構

用Dijkstra算法找出以A爲起點的單源最短路徑步驟以下app

 

算法實現測試

      在具體的實現以前,咱們先有一個基礎的約定,就是途中的每個節點咱們都用正整數進行編碼,相鄰兩點之間的距離是正整數,圖中兩個直接相鄰兩點的距離咱們保存到map中,也就是求最短距離咱們須要實現這樣的一個方法:this

 

[java] view plain copy編碼

 print?在CODE上查看代碼片派生到個人代碼片spa

  1. public MinStep getMinStep(int start, int end, final HashMap<Integer, HashMap<Integer, Integer>> stepLength);  

 

      第一個參數是起始節點的編號,第二個參數是終點節點的編號,第三個參數是圖中直接相鄰兩個節點的距離組成的map。關於第三個參數,會在後面作詳細的介紹。這裏咱們定義一個接口,用於計算兩點之間的最短路徑,具體以下:

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1.  /**   
  2.  *@Description:      
  3.  */   
  4. package com.lulei.distance;    
  5.   
  6. import java.util.HashMap;  
  7.   
  8. import com.lulei.distance.bean.MinStep;  
  9.     
  10. public interface Distance {  
  11.     public static final MinStep UNREACHABLE = new MinStep(false, -1);  
  12.     /** 
  13.      * @param start 
  14.      * @param end 
  15.      * @param stepLength 
  16.      * @return 
  17.      * @Author:lulei   
  18.      * @Description: 起點到終點的最短路徑 
  19.      */  
  20.     public MinStep getMinStep(int start, int end, final HashMap<Integer, HashMap<Integer, Integer>> stepLength);  
  21. }  

 

 

1、方法返回值介紹

      上面方法的返回值是咱們自定義的一個數據類型,下面咱們經過代碼來看其具體的數據結構

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1. /**   
  2.  *@Description:      
  3.  */  
  4. package com.lulei.distance.bean;  
  5.   
  6. import java.util.List;  
  7.   
  8. public class MinStep {  
  9.     private boolean reachable;//是否可達  
  10.     private int minStep;//最短步長  
  11.     private List<Integer> step;//最短路徑  
  12.   
  13.     public MinStep() {  
  14.     }  
  15.       
  16.     public MinStep(boolean reachable, int minStep) {  
  17.         this.reachable = reachable;  
  18.         this.minStep = minStep;  
  19.     }  
  20.   
  21.     public boolean isReachable() {  
  22.         return reachable;  
  23.     }  
  24.     public void setReachable(boolean reachable) {  
  25.         this.reachable = reachable;  
  26.     }  
  27.     public int getMinStep() {  
  28.         return minStep;  
  29.     }  
  30.     public void setMinStep(int minStep) {  
  31.         this.minStep = minStep;  
  32.     }  
  33.     public List<Integer> getStep() {  
  34.         return step;  
  35.     }  
  36.     public void setStep(List<Integer> step) {  
  37.         this.step = step;  
  38.     }  
  39. }  


      其中最短路徑的那個List數組保存了從起點到終點最短路徑所經歷的節點。

 

 

2、每個節點的最優前一節點

      在迪傑斯特拉算法中咱們須要保存從起點開始到每個節點最短步長,這也是圖中須要比較得出的步長,同時咱們還須要存儲該步長下的前一個節點是哪一個,這樣咱們就能夠經過終點一個一個往前推到起點,這樣就出來了完整的最優路徑。

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1. /**   
  2.  *@Description:      
  3.  */  
  4. package com.lulei.distance.bean;  
  5.   
  6. public class PreNode {  
  7.     private int preNodeNum;// 最優 前一個節點  
  8.     private int nodeStep;// 最小步長  
  9.   
  10.     public PreNode(int preNodeNum, int nodeStep) {  
  11.         this.preNodeNum = preNodeNum;  
  12.         this.nodeStep = nodeStep;  
  13.     }  
  14.   
  15.     public int getPreNodeNum() {  
  16.         return preNodeNum;  
  17.     }  
  18.     public void setPreNodeNum(int preNodeNum) {  
  19.         this.preNodeNum = preNodeNum;  
  20.     }  
  21.     public int getNodeStep() {  
  22.         return nodeStep;  
  23.     }  
  24.     public void setNodeStep(int nodeStep) {  
  25.         this.nodeStep = nodeStep;  
  26.     }  
  27. }  


3、迪傑斯特拉算法計算過程當中須要關注的變量

 

      從介紹迪傑斯特拉算法的圖中,咱們知道在計算的過程當中咱們須要保存起點到各個節點的最短距離、已經計算過的節點、下次須要計算節點隊列和圖中相鄰兩個節點的距離。咱們經過代碼來看下具體的定義:

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1. //key1節點編號,key2節點編號,value爲key1到key2的步長  
  2. private HashMap<Integer, HashMap<Integer, Integer>> stepLength;  
  3. //非獨立節點個數  
  4. private int nodeNum;  
  5. //移除節點  
  6. private HashSet<Integer> outNode;  
  7. //起點到各點的步長,key爲目的節點,value爲到目的節點的步長  
  8. private HashMap<Integer, PreNode> nodeStep;  
  9. //下一次計算的節點  
  10. private LinkedList<Integer> nextNode;  
  11. //起點、終點  
  12. private int startNode;  
  13. private int endNode;  

 

      咱們這裏看下stepLength這個屬性,它保存了圖中相鄰兩個節點之間的距離,好比key1=1;key2=3;value=9;這表明的意義就是從節點1到節點3的距離是9。經過這樣的存儲,咱們就須要把圖中每兩個相鄰的點保存到這個類型的map中。

 

4、屬性初始化

      在開始計算以前,咱們須要對這些屬性進行初始化,具體以下:

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1. private void initProperty(int start, int end) {  
  2.     outNode = new HashSet<Integer>();  
  3.     nodeStep = new HashMap<Integer, PreNode>();  
  4.     nextNode = new LinkedList<Integer>();  
  5.     nextNode.add(start);  
  6.     startNode = start;  
  7.     endNode = end;  
  8. }  


       這一步咱們須要把起點添加到下一次須要計算的節點隊列中。

 

 

5、迪傑斯特拉算法

      這一步也就是迪傑斯特拉算法的核心部分,在計算的過程當中,咱們須要進行以下步驟:

1)判斷是否達到終止條件,若是達到終止條件,結束本次算法,若是沒有達到,執行下一步;(終止條件:下一次須要計算的節點隊列沒有數據或已經計算過的節點數等於節點總數)

2)獲取下一次計算的節點A;

3)從起點到各節點之間的最短距離map中獲取到達A點的最小距離L;

4)獲取A節點的可達節點B,計算從起點先到A再到B是否優於已有的其餘方式到B,若是優於,則更新B節點,不然不更新;

5)判斷B是不是已經移除的節點,若是不是移除的節點,把B添加到下一次須要計算的節點隊列中,不然不作操做;

6)判斷A節點是否還有除B之外的其餘節點,若是有,執行第4)步,不然執行下一步;

7)將A節點從下一次須要計算的節點中移除添加到已經計算過的節點中;

8)執行第一步。

      咱們來看下具體的代碼實現:

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1. private void step() {  
  2.     if (nextNode == null || nextNode.size() < 1) {  
  3.         return;  
  4.     }  
  5.     if (outNode.size() == nodeNum) {  
  6.         return;  
  7.     }  
  8.     //獲取下一個計算節點  
  9.     int start = nextNode.removeFirst();  
  10.     //到達該節點的最小距離  
  11.     int step = 0;  
  12.     if (nodeStep.containsKey(start)) {  
  13.         step = nodeStep.get(start).getNodeStep();  
  14.     }  
  15.     //獲取該節點可達節點  
  16.     HashMap<Integer,Integer> nextStep = stepLength.get(start);  
  17.     Iterator<Entry<Integer, Integer>> iter = nextStep.entrySet().iterator();  
  18.     while (iter.hasNext()) {  
  19.         Entry<Integer, Integer> entry = iter.next();  
  20.         Integer key = entry.getKey();  
  21.         //若是是起點到起點,不計算之間的步長  
  22.         if (key == startNode) {  
  23.             continue;  
  24.         }  
  25.         //起點到可達節點的距離  
  26.         Integer value = entry.getValue() + step;  
  27.         if ((!nextNode.contains(key)) && (!outNode.contains(key))) {  
  28.             nextNode.add(key);  
  29.         }  
  30.         if (nodeStep.containsKey(key)) {  
  31.             if (value < nodeStep.get(key).getNodeStep()) {  
  32.                 nodeStep.put(key, new PreNode(start, value));  
  33.             }  
  34.         } else {  
  35.             nodeStep.put(key, new PreNode(start, value));  
  36.         }  
  37.     }  
  38.     //將該節點移除  
  39.     outNode.add(start);  
  40.     //計算下一個節點  
  41.     step();  
  42. }  

 

6、組裝最短路徑返回結果

      經過前面的計算,已經計算出了起點到各個節點的最短路徑,下面就須要組裝起點到終點的最短路徑,在計算最短距離下的路徑方式,咱們須要從終點依次往前推,即到達終點最短距離下的前一個節點是A,到達A節點最短距離下的前一節點是B,直到找到起點終止。

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1. private MinStep changeToMinStep() {  
  2.     MinStep minStep = new MinStep();  
  3.     minStep.setMinStep(nodeStep.get(endNode).getNodeStep());  
  4.     minStep.setReachable(true);  
  5.     LinkedList<Integer> step = new LinkedList<Integer>();  
  6.     minStep.setStep(step);  
  7.     int nodeNum = endNode;  
  8.     step.addFirst(nodeNum);  
  9.     while (nodeStep.containsKey(nodeNum)) {  
  10.         int node = nodeStep.get(nodeNum).getPreNodeNum();  
  11.         step.addFirst(node);  
  12.         nodeNum = node;  
  13.     }  
  14.     return minStep;  
  15. }  


7、接口定義方法實現

 

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1. public MinStep getMinStep(int start, int end, final HashMap<Integer, HashMap<Integer, Integer>> stepLength) {  
  2.     this.stepLength = stepLength;  
  3.     this.nodeNum = this.stepLength != null ? this.stepLength.size() : 0;  
  4.     //起點、終點不在目標節點內,返回不可達  
  5.     if (this.stepLength == null || (!this.stepLength.containsKey(start)) || (!this.stepLength.containsKey(end))) {  
  6.         return UNREACHABLE;  
  7.     }  
  8.     initProperty(start, end);  
  9.     step();  
  10.     if (nodeStep.containsKey(end)) {  
  11.         return changeToMinStep();  
  12.     }  
  13.     return UNREACHABLE;  
  14. }  


8、迪傑斯特拉算法完整代碼

 

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1. /**   
  2.  *@Description:      
  3.  */  
  4. package com.lulei.distance.dijkstra;  
  5.   
  6. import java.util.HashMap;  
  7. import java.util.HashSet;  
  8. import java.util.Iterator;  
  9. import java.util.LinkedList;  
  10. import java.util.Map.Entry;  
  11.   
  12. import com.lulei.distance.Distance;  
  13. import com.lulei.distance.bean.MinStep;  
  14. import com.lulei.distance.bean.PreNode;  
  15.   
  16. public class DistanceDijkstraImpl implements Distance{  
  17.     //key1節點編號,key2節點編號,value爲key1到key2的步長  
  18.     private HashMap<Integer, HashMap<Integer, Integer>> stepLength;  
  19.     //非獨立節點個數  
  20.     private int nodeNum;  
  21.     //移除節點  
  22.     private HashSet<Integer> outNode;  
  23.     //起點到各點的步長,key爲目的節點,value爲到目的節點的步長  
  24.     private HashMap<Integer, PreNode> nodeStep;  
  25.     //下一次計算的節點  
  26.     private LinkedList<Integer> nextNode;  
  27.     //起點、終點  
  28.     private int startNode;  
  29.     private int endNode;  
  30.       
  31.     /** 
  32.      * @param start 
  33.      * @param end 
  34.      * @param stepLength 
  35.      * @return 
  36.      * @Author:lulei   
  37.      * @Description: start 到 end 的最短距離 
  38.      */  
  39.     public MinStep getMinStep(int start, int end, final HashMap<Integer, HashMap<Integer, Integer>> stepLength) {  
  40.         this.stepLength = stepLength;  
  41.         this.nodeNum = this.stepLength != null ? this.stepLength.size() : 0;  
  42.         //起點、終點不在目標節點內,返回不可達  
  43.         if (this.stepLength == null || (!this.stepLength.containsKey(start)) || (!this.stepLength.containsKey(end))) {  
  44.             return UNREACHABLE;  
  45.         }  
  46.         initProperty(start, end);  
  47.         step();  
  48.         if (nodeStep.containsKey(end)) {  
  49.             return changeToMinStep();  
  50.         }  
  51.         return UNREACHABLE;  
  52.     }  
  53.       
  54.     /** 
  55.      * 返回最短距離以及路徑 
  56.      */  
  57.     private MinStep changeToMinStep() {  
  58.         MinStep minStep = new MinStep();  
  59.         minStep.setMinStep(nodeStep.get(endNode).getNodeStep());  
  60.         minStep.setReachable(true);  
  61.         LinkedList<Integer> step = new LinkedList<Integer>();  
  62.         minStep.setStep(step);  
  63.         int nodeNum = endNode;  
  64.         step.addFirst(nodeNum);  
  65.         while (nodeStep.containsKey(nodeNum)) {  
  66.             int node = nodeStep.get(nodeNum).getPreNodeNum();  
  67.             step.addFirst(node);  
  68.             nodeNum = node;  
  69.         }  
  70.         return minStep;  
  71.     }  
  72.       
  73.     /** 
  74.      * @param start 
  75.      * @Author:lulei   
  76.      * @Description: 初始化屬性 
  77.      */  
  78.     private void initProperty(int start, int end) {  
  79.         outNode = new HashSet<Integer>();  
  80.         nodeStep = new HashMap<Integer, PreNode>();  
  81.         nextNode = new LinkedList<Integer>();  
  82.         nextNode.add(start);  
  83.         startNode = start;  
  84.         endNode = end;  
  85.     }  
  86.       
  87.     /** 
  88.      * @param end 
  89.      * @Author:lulei   
  90.      * @Description: 
  91.      */  
  92.     private void step() {  
  93.         if (nextNode == null || nextNode.size() < 1) {  
  94.             return;  
  95.         }  
  96.         if (outNode.size() == nodeNum) {  
  97.             return;  
  98.         }  
  99.         //獲取下一個計算節點  
  100.         int start = nextNode.removeFirst();  
  101.         //到達該節點的最小距離  
  102.         int step = 0;  
  103.         if (nodeStep.containsKey(start)) {  
  104.             step = nodeStep.get(start).getNodeStep();  
  105.         }  
  106.         //獲取該節點可達節點  
  107.         HashMap<Integer,Integer> nextStep = stepLength.get(start);  
  108.         Iterator<Entry<Integer, Integer>> iter = nextStep.entrySet().iterator();  
  109.         while (iter.hasNext()) {  
  110.             Entry<Integer, Integer> entry = iter.next();  
  111.             Integer key = entry.getKey();  
  112.             //若是是起點到起點,不計算之間的步長  
  113.             if (key == startNode) {  
  114.                 continue;  
  115.             }  
  116.             //起點到可達節點的距離  
  117.             Integer value = entry.getValue() + step;  
  118.             if ((!nextNode.contains(key)) && (!outNode.contains(key))) {  
  119.                 nextNode.add(key);  
  120.             }  
  121.             if (nodeStep.containsKey(key)) {  
  122.                 if (value < nodeStep.get(key).getNodeStep()) {  
  123.                     nodeStep.put(key, new PreNode(start, value));  
  124.                 }  
  125.             } else {  
  126.                 nodeStep.put(key, new PreNode(start, value));  
  127.             }  
  128.         }  
  129.         //將該節點移除  
  130.         outNode.add(start);  
  131.         //計算下一個節點  
  132.         step();  
  133.     }  
  134. }  


 

 

代碼測試

     對於上述代碼的測試,咱們仍是使用咱們事例圖形中的例子,計算從節點1到節點5的最短距離。

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1.  /**   
  2.  *@Description:      
  3.  */   
  4. package com.lulei.distance.test;    
  5.   
  6. import java.util.HashMap;  
  7.   
  8. import com.lulei.distance.Distance;  
  9. import com.lulei.distance.bean.MinStep;  
  10. import com.lulei.distance.dijkstra.DistanceDijkstraImpl;  
  11. import com.lulei.util.JsonUtil;  
  12.     
  13. public class DistanceTest {  
  14.   
  15.     public static void main(String[] args) {  
  16.         // TODO Auto-generated method stub    
  17.         HashMap<Integer, HashMap<Integer,Integer>> stepLength = new HashMap<Integer, HashMap<Integer,Integer>>();  
  18.         HashMap<Integer,Integer> step1 = new HashMap<Integer, Integer>();  
  19.         stepLength.put(1, step1);  
  20.         step1.put(6, 14);  
  21.         step1.put(3, 9);  
  22.         step1.put(2, 7);  
  23.           
  24.         HashMap<Integer,Integer> step2 = new HashMap<Integer, Integer>();  
  25.         stepLength.put(2, step2);  
  26.         step2.put(1, 7);  
  27.         step2.put(3, 10);  
  28.         step2.put(4, 15);  
  29.           
  30.         HashMap<Integer,Integer> step3 = new HashMap<Integer, Integer>();  
  31.         stepLength.put(3, step3);  
  32.         step3.put(1, 9);  
  33.         step3.put(2, 10);  
  34.         step3.put(4, 11);  
  35.         step3.put(6, 2);  
  36.           
  37.         HashMap<Integer,Integer> step4 = new HashMap<Integer, Integer>();  
  38.         stepLength.put(4, step4);  
  39.         step4.put(2, 15);  
  40.         step4.put(5, 5);  
  41.         step4.put(3, 11);  
  42.           
  43.         HashMap<Integer,Integer> step5 = new HashMap<Integer, Integer>();  
  44.         stepLength.put(5, step5);  
  45.         step5.put(6, 9);  
  46.         step5.put(4, 5);  
  47.           
  48.         HashMap<Integer,Integer> step6 = new HashMap<Integer, Integer>();  
  49.         stepLength.put(6, step6);  
  50.         step6.put(1, 14);  
  51.         step6.put(5, 9);  
  52.         step6.put(3, 2);  
  53.           
  54.         Distance distance = new DistanceDijkstraImpl();  
  55.         MinStep step = distance.getMinStep(1, 5, stepLength);  
  56.         System.out.println(JsonUtil.parseJson(step));  
  57.     }  
  58.   
  59. }  


      這裏組裝相鄰兩個節點之間的距離用了大量的代碼,咱們看下輸出結果:

 

 

[java] view plain copy

 print?在CODE上查看代碼片派生到個人代碼片

  1. {"reachable":true,"minStep":20,"step":[1,3,6,5]}  


 

 

最後的思考

      最短路徑算法在現實生活中其實有不少的用處,好比迷宮解法、路徑規劃、路由尋址等等,這些問題看似很複雜,其實只須要作對應的轉化後仍是能夠用最基礎的算法解決的。

相關文章
相關標籤/搜索