|
| 1 | +package org.ucf.java.Dijkstra; |
| 2 | +import org.ucf.java.common.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * Created by Bing on 3/17/2016. |
| 7 | + */ |
| 8 | + |
| 9 | +public class Dijkstra { |
| 10 | + public Set<Node> open; // to store nodes which does not deal with |
| 11 | + public Set<Node> close; // to store sort results |
| 12 | + public Set<Edge> path; // to store the edge information |
| 13 | + public Node start; |
| 14 | + |
| 15 | + public Dijkstra(Set<Node> vertex,Node root) { |
| 16 | + this.open = new HashSet<Node>(vertex); |
| 17 | + this.close = new HashSet<Node>(); |
| 18 | + this.path = new HashSet<Edge>(); |
| 19 | + this.start = root; |
| 20 | + } |
| 21 | + public void computePath() { |
| 22 | + start.setDistance(0); |
| 23 | + close.add(start); |
| 24 | + open.remove(start); |
| 25 | + System.out.println("start node is:"+start.getName()); |
| 26 | + while (!open.isEmpty()) { |
| 27 | + Iterator<Node> it = close.iterator(); |
| 28 | + Edge edge = new Edge(null, null, Integer.MAX_VALUE); |
| 29 | + while (it.hasNext()) { |
| 30 | + Node node = it.next(); |
| 31 | + node.getShortestPath(open,edge); |
| 32 | + } |
| 33 | + path.add(edge); |
| 34 | + close.add(edge.getDst()); |
| 35 | + edge.getDst().setDistance(edge.getWeight()); |
| 36 | + edge.getDst().getChild().remove(edge.getSrc()); |
| 37 | + |
| 38 | + edge.getSrc().getChild().remove(edge.getDst()); |
| 39 | + open.remove(edge.getDst()); |
| 40 | + } |
| 41 | + } |
| 42 | + public void findpath(Node e,List<Edge> link) { |
| 43 | + Iterator<Edge> it = path.iterator(); |
| 44 | + while(it.hasNext()) { |
| 45 | + Edge edg = it.next(); |
| 46 | + if(edg.getDst().equals(e) == true){ |
| 47 | + link.add(edg); |
| 48 | + findpath(edg.getSrc(),link); |
| 49 | + } |
| 50 | + } |
| 51 | + if(e.equals(start) == true) { |
| 52 | + if(link.isEmpty() == true) |
| 53 | + link.add(new Edge(e,e,e.getDistance())); |
| 54 | + return; |
| 55 | + } |
| 56 | + } |
| 57 | + public void printedges(){ |
| 58 | + Iterator<Edge> it = path.iterator(); |
| 59 | + while (it.hasNext()){ |
| 60 | + Edge link = it.next(); |
| 61 | + link.printinfo(); |
| 62 | + } |
| 63 | + } |
| 64 | + public void printpath(Node node){ |
| 65 | + List<Edge> path = new ArrayList<Edge>(); |
| 66 | + this.findpath(node,path); |
| 67 | + for(int i=path.size()-1;i>=0;i--) { |
| 68 | + Edge it = path.get(i); |
| 69 | + if(i == path.size() -1){ |
| 70 | + System.out.print("The Destination Node: "+path.get(0).getDst().getName()+"\t"); |
| 71 | + System.out.print("\tPath value ="+path.get(0).getWeight()+"\t Path is: "); |
| 72 | + System.out.print(it.getSrc().getName()+"->"+it.getDst().getName()); |
| 73 | + } else{ |
| 74 | + System.out.print("->"+it.getDst().getName()); |
| 75 | + } |
| 76 | + if(i == 0) |
| 77 | + System.out.println(); |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments