Java实现Dijkstra(迪杰斯特拉)算法

话不多说,上代码:


public class Dijkstra {

	private Map topoMap = new HashMap();

	private List> resultPath = new ArrayList>();
	private List shortestPath = new ArrayList();
	private Stack currentPath = new Stack();
	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 nextHop;

		DijkstaNode(Object obj, List 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 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 finishList = new ArrayList(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 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 getShortestPath(){
		return shortestPath;
	}
	
	public List> getAllPath(){
		return resultPath;
	}
} 
  

你可能感兴趣的:(Java实现Dijkstra(迪杰斯特拉)算法)