Question: Build Dijkistra's algorithm using a min heap in JAVA . The program must be able to insert a new pathway and delete a pathway between
Build Dijkistra's algorithm using a min heap in JAVA. The program must be able to insert a new pathway and delete a pathway between two points. Not only that but prints out the shortest distance between two points and shows the pathway to get to Point B. Example: A -> E -> C -> B
Please include the output of the program. Min Heap code here:
public class MinHeap
{ private int[] Heap;
private int size;
private int maxsize;
private static final int FRONT = 1;
public MinHeap(int maxsize)
{ this.maxsize = maxsize;
this.size = 0;
Heap = new int[this.maxsize + 1];
Heap[0] = Integer.MIN_VALUE;
}
private int parent(int pos)
{ return pos / 2;
}
private int leftChild(int pos)
{ return (2 * pos);
}
private int rightChild(int pos)
{ return (2 * pos) + 1;
}
private boolean isLeaf(int pos)
{ if (pos >= (size / 2) && pos <= size)
{ return true;
}
return false;
}
private void swap(int fpos, int spos)
{ int tmp;
tmp = Heap[fpos];
Heap[fpos] = Heap[spos];
Heap[spos] = tmp;
}
private void minHeapify(int pos)
{ if (!isLeaf(pos))
{ if ( Heap[pos] > Heap[leftChild(pos)] || Heap[pos] > Heap[rightChild(pos)])
{ if (Heap[leftChild(pos)] < Heap[rightChild(pos)])
{ swap(pos, leftChild(pos));
minHeapify(leftChild(pos));
}else
{ swap(pos, rightChild(pos));
minHeapify(rightChild(pos));
}
}
}
}
public void insert(int element)
{ Heap[++size] = element;
int current = size;
while (Heap[current] < Heap[parent(current)])
{ swap(current,parent(current));
current = parent(current);
}
}
public void print()
{ for (int i = 1; i <= size / 2; i++ )
{ System.out.print(" PARENT : " + Heap[i] + " LEFT CHILD : " + Heap[2*i] + " RIGHT CHILD :" + Heap[2 * i + 1]);
System.out.println();
}
}
public void minHeap()
{ for (int pos = (size / 2); pos >= 1 ; pos--)
{ minHeapify(pos);
}
}
public int remove()
{ int popped = Heap[FRONT];
Heap[FRONT] = Heap[size--];
minHeapify(FRONT);
return popped;
} }
Here is the graph for Dijkistra's algorithm: The first and second Columns is from point A to point B. The third Column is the distance between two points 1 19 36 1 4 212 1 2 732 2 9 111 2 1 66 2 12 29 2 19 14 2 17 65 3 2 17 3 11 38 3 14 122 3 17 211 3 1 390 3 18 78 3 9 11 4 3 273 4 5 29 4 12 42 5 4 122 5 16 12 5 20 102 5 9 32 6 5 211 6 1 62 6 8 132 6 12 871 7 11 122 7 2 200 7 13 81 7 4 41 7 1 20 7 14 11 8 6 5 8 3 210 8 16 74 9 2 95 9 11 2 9 7 120 9 20 11 10 12 121 10 20 653 10 3 925 11 2 81 11 12 219 11 4 90 11 16 211 12 19 122 12 8 390 12 5 98 12 7 122 12 3 11 13 9 9 12 17 121 13 17 26 13 1 719 13 20 832 14 20 219 14 10 182 14 9 13 14 3 22 15 6 22 16 11 73 16 18 98 17 20 190 17 1 77 17 11 21 17 12 93 17 9 200 18 10 33 18 16 940 18 8 29 18 20 121 18 15 33 19 2 322 19 5 74 19 6 219 19 10 111
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
