For the past few days I've tried to implement this algorithm. This far I've managed to make a dynamic 2d array and insert the distances between nodes, a function to remove a path between nodes and a function that tells me if there is a path between two nodes. Now I would like to implement a function that returns the shortest path from node A to node B. I know how dijkstras algorithm works and I've read the pseudo code on wiki without being able to write any code my self. I'm really stuck here.
I've been thinking about how the code should look like and what should happen thats why I've made that function that tells me if theres a path between two nodes. Do I need any more help functions which would make implementing of dijkstras easier?
For now I have only 3 nodes but the code I would like to write needs to work in general for n nodes.
Any kind of help is appreciated.
Approach: Starting from the source 'S', add it to the queue. Remove the first node from the queue and mark it visited so that it should not be processed again. For the node just removed from the queue in step 2, check all the neighboring nodes.
Approach: The solution is to perform BFS or DFS to find whether there is a path or not. The graph needs not to be created to perform the bfs, but the matrix itself will be used as a graph. Start the traversal from the top right corner and if there is a way to reach the bottom right corner then there is a path.
Dijkstra is DP! Or in order to qualify as dynamic algorithm I have to change a loop into a recursive function. As iterative functions save stack memory (as described in above ans) , some modern languages like kotlin automatically convert recursive functions into non recursive ones.
Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph. Examples: Input: src = 0, the graph is shown below.
You are probably thinking to much.
You need 2 things. A clean graph structure you understand. A good description of the algorithm you understand. If you have both. Just start writing some code. Helpers needed will become obvious on the way.
-- edit --
You will probably need some of the following datastructuresstd::vector
std::list
std::priority_queue
I found several codes for this algorithm, but maybe it is better the simplest one in order to undertand it better, so you can check the differences between yours and this one, and complete yours. It is always better to program your way.
Have a look at this one and see if it helps.
http://vinodcse.wordpress.com/2006/05/19/code-for-dijkstras-algorithm-in-c-2/
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With