For input
g.addVertex("A");
g.addVertex("B");
g.addVertex("C");
g.addVertex("D");
g.addVertex("E");
g.addVertex("F");
g.addVertex("G");
g.addEdge("A","B",2);
g.addEdge("A","D",5);
g.addEdge("B","C",3);
g.addEdge("C","D",1);
g.addEdge("D","E",8);
g.addEdge("E","F",5);
g.addEdge("E","G",7);
g.addEdge("F","G",9);
with method called g.dijkstra(“A”);
output received is
A A 0
B AB 2
C ABC 5
E 2147483647
G G -2147483642
D D -2147483641
F F -2147483644
for some reason D is not placed correctly in the min-heap
Code/Implementation below :
private class dPair implements Comparable<dPair>{
String val,path;
int cost;
@Override
public int compareTo(dPair o) {
return o.cost-this.cost;
}
@Override
public String toString(){
return val+" "+path+" "+cost;
}
}
public void dijkstra(String src){
HashMap<String,dPair>map=new HashMap<>();
Gen_Heap<dPair>heap=new Gen_Heap<>();
for(String here:this.vertices.keySet()){
dPair add=new dPair();
add.val=here;
add.path="";
add.cost=Integer.MAX_VALUE;
if(here.equals(src)){
add.path=here;
add.cost=0;
}
heap.add(add);
map.put(here,add);
}
while(!heap.isEmpty()){
dPair rem=heap.remove();
map.remove(rem.val);
System.out.println(rem);
Vertex here=this.vertices.get(rem.val);
for(String nbr:here.nbrs.keySet()){
if(map.containsKey(nbr)){
int oc=map.get(nbr).cost;
int nc=rem.cost+here.nbrs.get(nbr);
if(nc<oc){
dPair mod=map.get(nbr);
mod.cost=nc;
mod.path=rem.path+nbr;
heap.updatePriority(mod);
}
}
}
}
}