Since Java priority queue does not allow to update value of element in priority queue therefore I decided to use TreeSet in Java as an alternate of priority queue to implement Dijikstra shortest distance algorithm
. Since I can find element in treeSet with O(log n)
than I remove it and now I can insert new element in treeSet. TreeSet.first()
always give me a lowest value in treeSet. But this idea is not working. I don't know why?
public class Dijikstra {
public static void dik(int n,int adj[][]) {
TreeSet<nod> p= new TreeSet(new Mycompare());
boolean visit[] = new boolean[n];
nod a[] = new nod[n];
for(int i = 0; i < n; i++) {
a[i] =new nod();
a[i].dis = Integer.MAX_VALUE;
a[i].id = i;
if(i == 0) {
a[i].dis = 0;
}
p.add(a[i]);
}
while(p.isEmpty() == false) {
nod temp = p.first();
p.remove(p.first());
visit[temp.id] = true;
for(int i = 0; i < n; i++) {
if(visit[i] == false && adj[temp.id][i] != 0) {
if(a[i].dis > temp.dis + adj[temp.id][i]) {
p.remove(a[i]);
a[i].dis = temp.dis + adj[temp.id][i];
p.add(a[i]);
}
}
}
}
for(int i = 0; i < n; i++) {
System.out.println(a[i].id+ " " + a[i].dis);
}
}
}
above is my Dijikstra
class
my nod
class is
class nod {
int dis;
int id;
}
my Mycompare
class is
class Mycompare implements Comparator<nod> {
@Override
public int compare(nod t, nod t1) {
return t.dis - t1.dis;
}
}