简体   繁体   中英

Trouble understanding Priority Queue implementation of Dijkstra

I am having some trouble wrapping my head around what exactly is the logical flow in which we implement Dijkstra, more precisely what I am having a problem with is how do we actually GET that priority queue, do we build it ( the Priority Queue ) as we go about executing the algorithm on a graph? Or am I looking at this wrong? And then is that it? Do we stop there or do we process this output even further by placing the obtained information in the Priority Queue in some other form or is this is the place where we stop?

I also understand the procedure of producing the corresponding shortest paths which for a chosen node, by recursively following the edges that we took to form the shortest path in the first place, but how is it actually implemented?

In general I'm having a lot of problems actually being able to think up and/or understand suitable implementations of algorithms during my study, I understand the algorithm just fine ( and in some cases I am able to think of a close substitute ) but I just cannot think up clever ways of implementing them, any suggestions?

My best advice is to start with bfs first. If you can implement BFS, you are just one step away from Dijkstra. BFS uses normal queue (first in first out), Dijkstra uses priority queue (element is chosen according to the current distance to source node). That is the only difference.

To answer your specific question:

  • How do we actually GET that priority queue? You start with an empty queue. At every iteration (Dijkstra most often is implemented iteratively, not recursively), you pick the node with the highest priority out of the queue, and push back in queue all the neighbors of that node that have not been visited yet
  • do we build it ( the Priority Queue ) as we go about executing the algorithm on a graph? Yes, at every iteration, you pick out one node, and push in multiple nodes to the priority queue
  • And then is that it? Yes, it is pretty much it.
  • Minor details: (1) You need to keep track of which nodes that have been picked out (and never push it back in) (2) It is possible to push a node multiple times into the queue, and it is fine, (3) You need a trace array to trace back the path along which you reach the node: every time you push a node into the queue, record the trace of that node to be the currently visited node (just popped from the queue)

Again, start with BFS and you will find Dijkstra pretty simple

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM