话不多说,上代码:
public class Dijkstra {
private Map<Object, DijkstaNode> topoMap = new HashMap<Object, DijkstaNode>();
private List<List<Object>> resultPath = new ArrayList<List<Object>>();
private List<Object> shortestPath = new ArrayList<Object>();
private Stack<Object> currentPath = new Stack<Object>();
private DijkstaNode headNode = null;
private DijkstaNode endNode = null;
private int shortestLength = Integer.MAX_VALUE;
private int currentLength = 0;
Dijkstra(){
topoMap.clear();
headNode = null;
endNode = null;
resultPath.clear();
shortestPath.clear();
currentPath.clear();
shortestLength = Integer.MAX_VALUE;
currentLength = 0;
}
private class DijkstaNode {
boolean hasCross;
Object origNode;
List<Object> nextHop;
DijkstaNode(Object obj, List<Object> list) {
origNode = obj;
hasCross = false;
nextHop = list;
}
@Override
public boolean equals(Object arg0) {
// TODO Auto-generated method stub
return origNode.equals(arg0);
}
}
private void calculatePath(DijkstaNode head) {
List<Object> list = head.nextHop;
if (list.isEmpty())
{
return;
}
currentPath.push(head.origNode);
currentLength++;
System.out.println("-->push:" + head.origNode);
for (Object obj : list) {
DijkstaNode next = topoMap.get(obj);
if (next.hasCross) {
continue;
}
if (next.equals(endNode)){
currentPath.push(next.origNode);
System.out.println("-->push:" + next.origNode);
List<Object> finishList = new ArrayList<Object>(currentPath);
if (currentLength < shortestLength) {
shortestLength = currentLength;
shortestPath = finishList;
}
resultPath.add(finishList);
currentPath.pop();
System.out.println("-->pop:" + next.origNode);
continue;
}
next.hasCross = true;
this.calculatePath(next);
next.hasCross = false;
}
currentPath.pop();
currentLength--;
System.out.println("-->pop:" + head.origNode);
}
public void addTopoMapNode(Object node, List<Object> nextHopList) {
DijkstaNode newNode = new DijkstaNode(node, nextHopList);
topoMap.put(node, newNode);
}
public void setStartNode(Object node) {
if (headNode != null) {
throw new RuntimeException();
}
DijkstaNode newNode = topoMap.get(node);
headNode = newNode;
}
public void setEndNode(Object node) {
if (endNode != null) {
throw new RuntimeException();
}
DijkstaNode newNode = topoMap.get(node);
endNode = newNode;
}
public void startCalculate(){
if (headNode == null || endNode == null){
throw new RuntimeException();
}
this.calculatePath(headNode);
}
public void resetCalculateResult() {
headNode = null;
endNode = null;
resultPath.clear();
shortestPath.clear();
currentPath.clear();
shortestLength = Integer.MAX_VALUE;
currentLength = 0;
}
public void resetTopoMap(){
topoMap.clear();
}
public List<Object> getShortestPath(){
return shortestPath;
}
public List<List<Object>> getAllPath(){
return resultPath;
}
}