java實現Dijkstra算法求最短路徑

Dijkstra(迪傑斯特拉)算法是典型的最短路徑路由算法,用於計算一個節點到其餘全部節點的最短路徑。主要特色是以起始點爲中心向外層層擴展,直到擴展到終點爲止。 java

Dijkstra通常的表述一般有兩種方式,一種用永久和臨時標號方式,一種是用OPEN, CLOSE表方式
用OPEN,CLOSE表的方式,其採用的是貪心法的算法策略,大概過程以下:
1.聲明兩個集合,open和close,open用於存儲未遍歷的節點,close用來存儲已遍歷的節點
2.初始階段,將初始節點放入close,其餘全部節點放入open
3.以初始節點爲中心向外一層層遍歷,獲取離指定節點最近的子節點放入close並重新計算路徑,直至close包含全部子節點 node

代碼實例以下:
Node對象用於封裝節點信息,包括名字和子節點 算法

public class Node { 
    private String name; 
    private Map<Node,Integer> child=new HashMap<Node,Integer>(); 
    public Node(String name){ 
        this.name=name; 
    } 
    public String getName() { 
        return name; 
    } 
    public void setName(String name) { 
        this.name = name; 
    } 
    public Map<Node, Integer> getChild() { 
        return child; 
    } 
    public void setChild(Map<Node, Integer> child) { 
        this.child = child; 
    } 
}

MapBuilder用於初始化數據源,返回圖的起始節點 數組

public class MapBuilder { 
    public Node build(Set<Node> open, Set<Node> close){ 
        Node nodeA=new Node("A"); 
        Node nodeB=new Node("B"); 
        Node nodeC=new Node("C"); 
        Node nodeD=new Node("D"); 
        Node nodeE=new Node("E"); 
        Node nodeF=new Node("F"); 
        Node nodeG=new Node("G"); 
        Node nodeH=new Node("H"); 
        nodeA.getChild().put(nodeB, 1); 
        nodeA.getChild().put(nodeC, 1); 
        nodeA.getChild().put(nodeD, 4); 
        nodeA.getChild().put(nodeG, 5); 
        nodeA.getChild().put(nodeF, 2); 
        nodeB.getChild().put(nodeA, 1); 
        nodeB.getChild().put(nodeF, 2); 
        nodeB.getChild().put(nodeH, 4); 
        nodeC.getChild().put(nodeA, 1); 
        nodeC.getChild().put(nodeG, 3); 
        nodeD.getChild().put(nodeA, 4); 
        nodeD.getChild().put(nodeE, 1); 
        nodeE.getChild().put(nodeD, 1); 
        nodeE.getChild().put(nodeF, 1); 
        nodeF.getChild().put(nodeE, 1); 
        nodeF.getChild().put(nodeB, 2); 
        nodeF.getChild().put(nodeA, 2); 
        nodeG.getChild().put(nodeC, 3); 
        nodeG.getChild().put(nodeA, 5); 
        nodeG.getChild().put(nodeH, 1); 
        nodeH.getChild().put(nodeB, 4); 
        nodeH.getChild().put(nodeG, 1); 
        open.add(nodeB); 
        open.add(nodeC); 
        open.add(nodeD); 
        open.add(nodeE); 
        open.add(nodeF); 
        open.add(nodeG); 
        open.add(nodeH); 
        close.add(nodeA); 
        return nodeA; 
    } 
}
圖的結構以下圖所示:


Dijkstra對象用於計算起始節點到全部其餘節點的最短路徑 測試

public class Dijkstra { 
    Set<Node> open=new HashSet<Node>(); 
    Set<Node> close=new HashSet<Node>(); 
    Map<String,Integer> path=new HashMap<String,Integer>();//封裝路徑距離 
    Map<String,String> pathInfo=new HashMap<String,String>();//封裝路徑信息 
    public Node init(){ 
        //初始路徑,因沒有A->E這條路徑,因此path(E)設置爲Integer.MAX_VALUE 
        path.put("B", 1); 
        pathInfo.put("B", "A->B"); 
        path.put("C", 1); 
        pathInfo.put("C", "A->C"); 
        path.put("D", 4); 
        pathInfo.put("D", "A->D"); 
        path.put("E", Integer.MAX_VALUE); 
        pathInfo.put("E", "A"); 
        path.put("F", 2); 
        pathInfo.put("F", "A->F"); 
        path.put("G", 5); 
        pathInfo.put("G", "A->G"); 
        path.put("H", Integer.MAX_VALUE); 
        pathInfo.put("H", "A"); 
        //將初始節點放入close,其餘節點放入open 
        Node start=new MapBuilder().build(open,close); 
        return start; 
    } 
    public void computePath(Node start){ 
        Node nearest=getShortestPath(start);//取距離start節點最近的子節點,放入close 
        if(nearest==null){ 
            return; 
        } 
        close.add(nearest); 
        open.remove(nearest); 
        Map<Node,Integer> childs=nearest.getChild(); 
        for(Node child:childs.keySet()){ 
            if(open.contains(child)){//若是子節點在open中 
                Integer newCompute=path.get(nearest.getName())+childs.get(child); 
                if(path.get(child.getName())>newCompute){//以前設置的距離大於新計算出來的距離 
                    path.put(child.getName(), newCompute); 
                    pathInfo.put(child.getName(), pathInfo.get(nearest.getName())+"->"+child.getName()); 
                } 
            } 
        } 
        computePath(start);//重複執行本身,確保全部子節點被遍歷 
        computePath(nearest);//向外一層層遞歸,直至全部頂點被遍歷 
    } 
    public void printPathInfo(){ 
        Set<Map.Entry<String, String>> pathInfos=pathInfo.entrySet(); 
        for(Map.Entry<String, String> pathInfo:pathInfos){ 
            System.out.println(pathInfo.getKey()+":"+pathInfo.getValue()); 
        } 
    } 
    /**
     * 獲取與node最近的子節點
     */ 
    private Node getShortestPath(Node node){ 
        Node res=null; 
        int minDis=Integer.MAX_VALUE; 
        Map<Node,Integer> childs=node.getChild(); 
        for(Node child:childs.keySet()){ 
            if(open.contains(child)){ 
                int distance=childs.get(child); 
                if(distance<minDis){ 
                    minDis=distance; 
                    res=child; 
                } 
            } 
        } 
        return res; 
    } 
} 

Main用於測試Dijkstra對象
public class Main { 
    public static void main(String[] args) { 
        Dijkstra test=new Dijkstra(); 
        Node start=test.init(); 
        test.computePath(start); 
        test.printPathInfo(); 
    } 
}

打印輸出以下:
D:A->D
E:A->F->E
F:A->F
G:A->C->G
B:A->B
C:A->C
H:A->B->H ui

矩陣實現: this

public class Dijkstra {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[][] weight = {
                {0,3,9999999,7,9999999},
                {3,0,4,2,9999999},
                {9999999,4,0,5,6},
                {7,2,5,0,4},
                {9999999,9999999,6,4,0}
        };
        
        int[] path = Dijsktra(weight,0);
        for(int i = 0;i < path.length;i++)
            System.out.print(path[i] + "  ");
    }
    

    public static int[] Dijsktra(int[][] weight,int start){
        //接受一個有向圖的權重矩陣,和一個起點編號start(從0編號,頂點存在數組中)
        //返回一個int[] 數組,表示從start到它的最短路徑長度
        int n = weight.length;        //頂點個數
        int[] shortPath = new int[n];    //存放從start到其餘各點的最短路徑
        int[] visited = new int[n];        //標記當前該頂點的最短路徑是否已經求出,1表示已求出
        
        //初始化,第一個頂點求出
        shortPath[start] = 0;
        visited[start] = 1;
        
        for(int count = 1;count <= n - 1;count++)        //要加入n-1個頂點
        {
            int k = -1;    //選出一個距離初始頂點start最近的未標記頂點
            int dmin = 1000;
            for(int i = 0;i < n;i++)
            {
                if(visited[i] == 0 && weight[start][i] < dmin)
                {
                    dmin = weight[start][i];
                    k = i;
                }    
            }
            
            //將新選出的頂點標記爲已求出最短路徑,且到start的最短路徑就是dmin
            shortPath[k] = dmin;
            visited[k] = 1;
            
            //以k爲中間點想,修正從start到未訪問各點的距離
            for(int i = 0;i < n;i++)
            {
                if(visited[i] == 0 && weight[start][k] + weight[k][i] < weight[start][i])
                     weight[start][i] = weight[start][k] + weight[k][i];
            }    
    
        }
        
        return shortPath;
    }
}
相關文章
相關標籤/搜索