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.