Search code examples
javaalgorithmheappriority-queuedijkstra

How priority queue is used with heap to solve min distance


Please bear with me I am very new to data structures.

I am getting confused how a priroity queue is used to solve min distance. For example if I have a matrix and want to find the min distance from the source to the destination, I know that I would perform Dijkstra algorithm in which with a queue I can easily find the distance between source and all elements in the matrix.

However, I am confused how a heap + priority queue is used here. For example say that I start at (1,1) on a grid and want to find the min distance to (3,3) I know how to implement the algorithm in the sense of finding the neighbours and checking the distances and marking as visited. But I have read about priority queues and min heaps and want to implement that.

Right now, my only understanding is a priority queue has a key to position elements. My issue is when I insert the first neighbours (1,0),(0,0),(2,1),(1,2) they are inserted in the pq based on a key (which would be distance in this case). So then the next search would be the element in the matrix with the shortest distance. But with the pq, how can a heap be used here with more then 2 neighbours? For example the children of (1,1) are the 4 neighbours stated above. This would go against the 2*i and 2*i + 1 and i/2

In conclusion, I don't understand how a min heap + priority queue works with finding the min of something like distance.

    0 1 2 3
     _ _ _ _
0 - |2|1|3|2|
1 - |1|3|5|1|
2 - |5|2|1|4|
3 - |2|4|2|1|

Solution

  • You need to use the priority queue to get the minimum weights in every move so the MinPQ will be fit for this.

    MinPQ uses internally technique of heap to put the elements in the right position operations such as sink() swim()

    So the MinPQ is the data structure that uses heap technique internally