Dijkstra(迪傑斯特拉)算法是典型的最短路徑路由算法
Dijkstra一般的表述通常有兩種方式
用OPEN
代碼實例如下
Node對象用於封裝節點信息
[java]
public class Node {
private String name;
private Map<Node
public Node(String name){
this
}
public String getName() {
return name;
}
public void setName(String name) {
this
}
public Map<Node
return child;
}
public void setChild(Map<Node
this
}
}
MapBuilder用於初始化數據源
[java]
public class MapBuilder {
public Node build(Set<Node> open
Node nodeA=new Node(
Node nodeB=new Node(
Node nodeC=new Node(
Node nodeD=new Node(
Node nodeE=new Node(
Node nodeF=new Node(
Node nodeG=new Node(
Node nodeH=new Node(
nodeA
nodeA
nodeA
nodeA
nodeA
nodeB
nodeB
nodeB
nodeC
nodeC
nodeD
nodeD
nodeE
nodeE
nodeF
nodeF
nodeF
nodeG
nodeG
nodeG
nodeH
nodeH
open
open
open
open
open
open
open
close
return nodeA;
}
}
圖的結構如下圖所示
Dijkstra對象用於計算起始節點到所有其他節點的最短路徑
[java]
public class Dijkstra {
Set<Node> open=new HashSet<Node>()
Set<Node> close=new HashSet<Node>()
Map<String
Map<String
public Node init(){
//初始路徑
path
pathInfo
path
pathInfo
path
pathInfo
path
pathInfo
path
pathInfo
path
pathInfo
path
pathInfo
//將初始節點放入close
Node start=new MapBuilder()
return start;
}
public void computePath(Node start){
Node nearest=getShortestPath(start)
if(nearest==null){
return;
}
close
open
Map<Node
for(Node child:childs
if(ntains(child)){//如果子節點在open中
Integer newCompute=path
if(path
path
pathInfo
}
}
}
computePath(start)
computePath(nearest)
}
public void printPathInfo(){
Set<Map
for(Map
System
}
}
/**
* 獲取與node最近的子節點
*/
private Node getShortestPath(Node node){
Node res=null;
int minDis=Integer
Map<Node
for(Node child:childs
if(ntains(child)){
int distance=childs
if(distance<minDis){
minDis=distance;
res=child;
}
}
}
return res;
}
}
Main用於測試Dijkstra對象
[java]
public class Main {
public static void main(String[] args) {
Dijkstra test=new Dijkstra()
Node start=test
putePath(start)
test
}
}
打印輸出如下
D:A
E:A
F:A
G:A
B:A
C:A
H:A
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26170.html