简体   繁体   中英

Dijkstra's algorithm pseudocode

I'm trying to write Dijkstra's algorithm in C++, and there are countless examples on the internet but I just can't seem to grasp how the examples work. I'd rather do it in a way that makes sense to me so I can understand the algorithm better. I know how the algorithm itself should work, and I have written some code. I was wondering if someone could point out the flaw in my thought process. I'm choosing to represent my graph as an edge list. I'll write in pseudocode because my actual code is a huge mess:

class Node{
   vector<node> linkVector;           //links to other nodes, generated at random
   int cost;                     //randomly generated by constructor
   bool visited = false;
}

vector<node> edgelist;           //contains all nodes


int main(){
   create n Nodes
   add all nodes to edgeList
   for each node {
      randomly add WEIGHT nodes to linkVector
   }
findPath(initialNode)
}

int findPath(Node start, node want, int cost=0){   //returns cost from src to dest
if(start==want) return cost;
if(every node has been visited) return 0;        //this is in case of failure
Node result = getMinimumCost()    //finds node in linkVector with least cost
result.visited(true)  //so we don't get stuck in a loop
findPath(result, want, result.getCost() + cost);  //recursive call
}

Via recursion, I'm trying to explore all the nodes until I find the one I'm looking for, then return and ride the cascading returns back up to the top of the function call stack, all the while adding up the total cost.

Performance doesn't really matter, but if using recursion makes it much harder than it needs to be, I am open to rewriting my code.

Dijkstra's algorithm isn't recursive. A recursive algorithm would end up being depth-first whereas Dijkstra's algorithm is a breadth-first search.

The central idea is that you have a priority queue of unvisited nodes. Each iteration you pull the node with the shortest distance off of the front of the queue and visit it. Then you update the distances to each of its unvisited neighbors.

A queue-based algorithm such as this does not lend itself to a recursive implementation. The search does not explore one path to exhaustion before it tries an alternate path as a depth-first search would do. It explores many paths simultaneously, only exploring them as long as they are the cheapest path. As soon as the current path is no longer the cheapest it moves on to another path. Recursion doesn't let you "jump" from path to path.

You can see this behavior in the graphic from the Wikipedia article .

在此处输入图片说明

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