|
Introduction
First of all I must say that I am glad that I can help CodeProject. I tried, and used code from this site and I never took the time to send some of my code. So, the part that it is missing from this site is the Algorithms part, which is important in the programming filed. Let's get into the problem now. The Djkstra algorithm it gives you a headache from the programming point of view. In one step it finds the shortest path to every node in the graph. I will go into the graph background (basics) and then I will present the implementation of this algorithm. This example has also some advanced programming techniques and technologies. I used an ActiveX control (that it is actually the Dijkstra solver) and a container application that use the functions. Also, the lists are made using STL
How to use it
First compile the AnimAlg project and then run the Algorithms project. That's all!
Background (graph theory)
Djikstra's algorithm (named after its discover, E.W. Dijkstra) solves the problem of finding the shortest path from a point in a graph (the source) to a destination. It turns out that one can find the shortest paths from a given source to all points in a graph in the same time, hence this problem is sometimes called the single-source shortest paths problem. The somewhat unexpected result that all the paths can be found as easily as one further demonstrates the value of reading the literature on algorithms!
This problem is related to the spanning tree one. The graph representing all the paths from one vertex to all the others must be a spanning tree - it must include all vertices. There will also be no cycles as a cycle would define more than one path from the selected vertex to at least one other vertex. For a graph,
G = (V,E) where V is a set of vertices and E is a set of edges. Dijkstra's algorithm keeps two sets of vertices: S the set of vertices whose shortest paths from the source have already been determined and V-S the remaining vertices. The other data structures needed are: d array of best estimates of shortest path to each vertex pi an array of predecessors for each vertex The basic mode of operation is: Initialize d and pi, Set S to empty, While there are still vertices in V-S, Sort the vertices in V-S according to the current best estimate of their distance from the source, Add u, the closest vertex in V-S, to S, Relax all the vertices still in V-S connected to u Relaxation The relaxation process updates the costs of all the vertices, v, connected to a vertex, u, if we could improve the best estimate of the shortest path to v by including (u,v) in the path to v.
Using the codeThe container application only use the ActiveX Control. First, must include the control in a Dialog or a FormView, add a variable to it and then use the following code: void CAlgorithmsView::OnAddNode()
{
m_Dijkstra.StartAddNodes();
}
void CAlgorithmsView::OnAddEdge()
{
m_Dijkstra.StartAddEdges();
}
void CAlgorithmsView::OnShortestPath()
{
CShorthestPath dlg;
if(dlg.DoModal()==IDOK)
{
m_Dijkstra.ShortestPath(dlg.m_node1, dlg.m_node2);
}
}
I will not go too much into the code, I tried to explain there using comments.
Basically, it respects the Graph Theory explained above and the Dijkstra's pseudocode.
Graph Implementationclass CGraph
{
public:
long GetNrNodes();
CGraph();
virtual ~CGraph();
VTYPE_NODE m_nodes;
VTYPE_EDGE m_edges;
VTYPE_NODE_P d;
VTYPE_NODE_P pi;
};class CNode
{
public:
CNode Copy();
double m_cost;
long m_NodeNr;
POINT m_p;
CNode();
virtual ~CNode();
};class CEdge
{
public:
bool m_red;
double m_cost;
long m_secondNode;
long m_firstNode;
POINT m_secondPct;
POINT m_firstPct;
CEdge();
virtual ~CEdge();
};
The Dijkstra's Algorithm (Implementation)
STDMETHODIMP CDijkstra::ShortestPath(long node1, long node2)
{
ReleaseGraph();
InitializeSource(g, g.m_nodes[node1-1]);
VTYPE_NODE S;
VTYPE_NODE Q;
VTYPE_NODE::iterator kl;
for(kl=g.m_nodes.begin(); kl<g.m_nodes.end(); kl++)
{
CNode node = (*kl).Copy();
Q.push_back(node);
}
while(Q.size())
{
CNode nod = ExtractMin(Q);
S.push_back(nod);
VTYPE_NODE::iterator kl;
for(kl=g.m_nodes.begin(); kl<g.m_nodes.end(); kl++)
{
if(ExistEdge(nod, (*kl)))
{
bool gasit = false;
VTYPE_NODE::iterator kll;
for(kll=Q.begin(); kll<Q.end(); kll++)
{
if((*kll).m_NodeNr == (*kl).m_NodeNr)
gasit = true;
}
if(gasit)
Relax(nod, (*kl), GetEdgeVal(nod, (*kl)));
}
}
}
RefreshDone(node1, node2);
return S_OK;
}
Links
If you want to see how the algorithm works step by step see the link: http://ciips.ee.uwa.edu.au/~morris/Year2/PLDS210/dij-op.html
| You must Sign In to use this message board. |
|
| | Msgs 1 to 23 of 23 (Total in Forum: 23) (Refresh) | FirstPrevNext |
|
|
 |
|
|
Hi, I am trying to implement a timer functionality to benchmark the algortihm, I want to see how long did the algorithm take to discover the shortest path. Can some one please please help me with that. Thanks
|
| Sign In·View Thread·PermaLink | 3.50/5 (2 votes) |
|
|
|
 |
|
|
Hi,
I implemented another Dijkstra Algorithm by using Java.
However, I feel my program which i wrote is not good enough if there are two way that can go to a target node with the same cost.
I saw the cisco's design. if there are more than one way to go toa ip with same cost, The default action of cisco router is making it load balancing.
I met the difficulty in the issue, and downloaded the source but cannot find the ans too, could you mind giving me some tips about this issue? thx.
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
I just want to know if any of you have tried algorithms on shortest path.Articles on shortest path(Dijsktra's algorithm) in this forum did not have a mechanism to create a node where edges criss-cross each other.It is required to create a topology of the road network to do so .Creation of topolgy needs finding of road intersections(beware of slope becoming infinity),which now become new nodes apart from existing nodes.The problem is complex/time-consuming if the road network is denser.Is there a simple way to create topolgy for a road network and then find shortest path?
|
| Sign In·View Thread·PermaLink | 1.67/5 (2 votes) |
|
|
|
 |
|
|
Hi all,
I want to implement Dijkstra's graph algo in C# , can anyone help me with code or useful links in this matter.
A code sample would do more help with complete implementation.
Desperately need help!
Ashish
|
| Sign In·View Thread·PermaLink | 1.67/5 (5 votes) |
|
|
|
 |
|
|
What do you have to do to make the algorithm find the shortest path through ALL the points with the condition that it can only go to each point once? I guess this is like the classic travelling salesman problem.
Thanks in advance
Stephen
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
hey, i was wondering if anyone knows where to find code for a VB version of dijkstra's algorithm. any help would be greatly appreciated.
-miro
|
| Sign In·View Thread·PermaLink | 2.00/5 (5 votes) |
|
|
|
 |
|
|
 |
|
|
 |
|
|
Bravo Frate e mijto programul. Vroiam si eu sa pun un algoritm al lui Dijkstra dar vad k l-ai pus tu. Daca ai cumva un algoritm bun de sortare si poti sa ma juti as fi recunoscator. Daca vrei putem tine legatura sa mai vb. Bafta!
gabby
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
You will implement a version of Dijkstra's algorithm with slightly enhanced "book-keeping" so that if there are several minimum distance paths from a source vertex to a destination vertex in a weighted directed graph, you will return the one that has the fewest number of edges. Recall that Dijkstra's algorithm, as described in the text, allows us to solve the single-source shortest weighted path problem: for a fixed source vertex s, we can calculate the shortest distance dv from s to v for every vertex v in the graph. The algorithm we have discussed also has "book-keeping" to allow us to reconstruct one path whose distance is equal to the minimum distance dv. Observe, however, that there can be several shortest distance paths from the source vertex s to the destination v. For example, consider the graph consisting of the following set of weighted directed edges, given by triples (from, to, cost): NYC LosAngeles 400 NYC SanFrancisco 700 NYC SanDiego 600 LosAngeles SanDiego 100 SanDiego SanFrancisco 100 LosAngeles SanFrancisco 200 Imagine, for example, that the edge cost represents the price of a one-way flight from the departure city to the arrival city (for a fairly unusual airline). Then there are two paths from NYC (New York City) to San Francisco with minimum cost of 600: NYC to LosAngeles to SanDiego to SanFrancisco NYC to LosAngeles to SanFrancisco Your program should return the second option, since that journey has only 2 legs rather than 3 legs. Your assignment is to implement an efficient version of Dijkstra's algorithm with extra book-keeping to allow the minimum distance path with fewest edges to be found. Only a few modifications to the pseudocode given in the text should be required. The main fact to keep in mind is the following (which is what makes the strategy in Dijkstra's algorithm work): If s = v1 v2 ... vi ... vN = v is a minimum length path from s to v, then for every vertex vi along the path, it must also be true that v1 v2 ... vi is a minimum length path from s to vi. Suggestion: first complete an efficient implementation of the Dijkstra's algorithm as given in the text, then think about what changes must be made to guarantee that you will also find the minimum cost path with fewest edges. Note that you should not keep track of all minimum length paths to do this. Technical requirements: · You must use a priority queue (heap) to allow you to efficiently find the unknown vertex with smallest distance for the main loop of Dijkstra's algorithm. You will need to extend the priority queue for allowing multiple entries for the same vertex and keeping track of whether vertices are known or unknown. · Read the graph from a text file. You should do at least minimal error checking, such as rejecting negative edges. See the sample input file, flights.txt for an example. · Allow the user to query source and destination vertices, and print out the minimum path with fewest edges using some kind of clear notation. Here is one example of acceptable output for the graph of cities given above: · Enter start node: · >NYC · Enter destination node: · >SanFrancisco · NYC -> LosAngeles -> SanFrancisco
NewYorkCity Boston 100 Chicago NewYorkCity 200 NewYorkCity Hartford 200 Rochester NewYorkCity 200 NewYorkCity Rochester 200 NewYorkCity Seattle 400 Seattle LosAngelese 100 LosAngelese Seattle 150 Seattle Vancouver 100 Vancouver LosAngelese 250 Vancouver SanDiego 300 SanDiego Seattle 200 Chicago SanFrancisco 300 SanFrancisco LosAngelese 200 Chicago LosAngelese 400 Chicago Toronto 350 NewYorkCity Toronto 250 Toronto NewYorkCity 300 NewYorkCity LosAngelese 400 NewYorkCity SanFrancisco 700 NewYorkCity SanDiego 600 LosAngelese SanDiego 100 SanDiego SanFrancisco 100 LosAngelese SanFrancisco 200
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hello, maybe sumone listen.
Well, i'm "soso" with c++ and this is not very clear to me.
Sum Questions: How to get notesdata in? Fortunately with Array. (with out clicking on form/non graphical aso..)
How to get calculated pathdata out?
Short: I need only the 3 Steps!
1.INPUT(notes,notes-exitnotes) -> 2.Algorithm -> 3.OUTPUT(notes)
Would be very nice if sumone would/could help me!
Sorry for bad English...greets
Rino
|
| Sign In·View Thread·PermaLink | 3.50/5 (2 votes) |
|
|
|
 |
|
|
You wrote: "The somewhat unexpected result that all the paths can be found as easily as one further demonstrates the value of reading the literature on algorithms!"
You will indeed find this statement frequently in the literature, and I was told it when I did CompSci. However, the reason it's a counter-inuitive result is that, in most cases of practical interest, it's not true! For example, I can find the shortest path from my home in Strathfield, Australia to the post office in Strathfield, Australia, without pulling out a map of Guatemala!
If you can supply a heuristic estimate of the shortest path between two nodes, you can use the A* (A star) algorithm which can be billions of times faster and more space-efficient than Dijkstra. You can always supply a heuristic in the important case of spatial coordinates (eg you can use the Euclidean distance between the two points). So for transportation problems, robotics, and most games, Dijkstra is _not_ the best algorithm. A* deserves to be much better known.
I'm not intending to disparage your work in any way, as Dijkstra is the best algorithm in the most general case. This comment is purely for your information. Some day, I will get around to posting my AStar implementation to CodeProject.
The moral of the story is: Your intuition is probably better than you think!
-Don.
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Everyone can find the shortest path on a desert, but in the mountains we can see which algorithm is better. As CompSci master you should know the difference between the optimal algorithm and the heuristic.
Regardless of the difference let's compare algorithms:
Input data: - Dijkstra alg. needs the map (graph), - A* needs the map and the heuristic estimate So, A* needs more data and effort to use it.
Result: - Dijkstra alg. always provides optimal solution - A* sometimes provides optimal solution So, quality of solutions provided by Dijkstra algorithm are bettter.
Algorithm complexity - worst case - Dijkstra alg. O(n^3) - A* O(B(n)*n^3), where B is complexity of the computation of the heuristic estimate. 'Billions of times faster' - you must be joking. OK, I can imagine the graph where it is true, but it is far from reality.
Memory used: I don't know the memory requirements of the A*, but Dijkstra alg. uses array/list of n elements, so what can be so more space-efficient. I've read somewhere that A* is infeasible for problems with huge number of nodes due to memory usage.
Finally I agree that for simple graphs (desert like) A* can be perfect.
The moral of the story is: Heuristic is never optimal
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
>As CompSci master you should know the difference >between the optimal algorithm and the heuristic.
> Heuristic is never optimal
True, but I think you've misunderstood the nature of A*. It is NOT a heuristic algorithm. You could in fact think of it as a specialised variant of Dijstra's algorithm to take advantage of additional information about the problem. In Dijstra's algorithm, you visit neighbouring nodes in a random order. In A*, you use the heuristic to pick which nodes to visit first. Both do exactly the same work, but A* changes the order to maximise the probability of getting finished quickly.
>Input data: >- Dijkstra alg. needs the map (graph), >- A* needs the map and the heuristic estimate >So, A* needs more data and effort to use it.
This is certainly true, if you want to get any advantage from it. But most workable heuristics are very simple.
>- Dijkstra alg. always provides optimal solution >- A* sometimes provides optimal solution
If the heuristic you've provided is 'admissible' (heuristic <= actual distance), then the A* algorithm is guaranteed to provide an optimal solution. I have seen a formal proof of this. A* is only an approximate algorithm if your heuristic overestimates the actual distance.
For all geographical/spatial paths you can use Euclidean distance as the heuristic. A* is always better than Dijkstra for this important case.
>Algorithm complexity - worst case >- Dijkstra alg. O(n^3) >- A* O(B(n)*n^3), where B is complexity of the computation of the heuristic estimate.
Actually the heuristic needs to be computed only once per node. So A* is in O(B(n) + n^3) = O(n^3) unless you have a fantastically stupid heuristic. In the worst case A* and Dijkstra are equal. The data structures used are virtually identical, so the memory requirements are similar.
For A*, it's more relevant to consider it in terms of p, the length of the shortest path, rather than n, the number of nodes. There is an equation I've seen but don't remember (on Gamasutra I think) that gives the complexity of A* as a function of p. It can be made independent of n.
>'Billions of times faster' - you must be joking. >OK, I can imagine the graph where it is true, but >it is far from reality. Yes, I was just emphasizing the point that an algorithm that is O(p^3) is much faster than an algorithm that is O(n^3)) where p << n, and is never worse because p is <= n by definition. Still, there are shortest-path algorithms for transport on the web where the user enters their location and destination. Such a system could conceivably include every road in the country, but most paths would be very short. It's not a completely contrived example.
The effectiveness of A* is as good as its heuristic. If you can provide a good one (and you frequently can), it is guaranteed to do much better than Dijkstra. This is true even for complex graphs. But if you don't have a heuristic, you should use Dijkstra because it's simpler to implement.
|
| Sign In·View Thread·PermaLink | 3.50/5 (2 votes) |
|
|
|
 |
|
|
A* (A-Star) is a variation of the WaveFront algorithm. It requires a "map" on which to run an hence suffers from the discreteness of grids. The grid must be finer than the closest pair of points (Nyquist limit). Satisfying this rule can lead to pathological problems if there are other points in the domain that are far away. Running an A Star on 10,000x10,000 grid will beat up your hard drive pretty bad when it goes virtual.
Ironically, if Dijkdstra's algorithm is converted from a list into... a matrix representation is is much faster for a manageable set of nodes. It too will begin to suffer when N > 1000.
|
| Sign In·View Thread·PermaLink | 3.00/5 (1 vote) |
|
|
|
 |
|
|
First: it is very good idea to present the algorithms in The Code Project.
Second: I'm not quite sure. I think the stop condition for the Dijkstra algorithm is: The vertex that currently has the shortest path is the destination vertex.
It is very important especially for large graphs used in real problems, because algorithm goes very quickly to the destination vertex and stops, then it doesn't calculate the complete network. Am I right?
Best regards
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
In the background the algorithm calculate the path to all nodes but I put in evidence (graphically) only the one I am interested in.
project manager Solid understanding of Microsoft technologies: Windows ActiveX, COM / DCOM and ATL, SDK, STL, WTL, MFC
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
I reviewed my files, and I found that we used this improvement of the Dijkstra algorithm for searching shortest path in single-source-single-destination problem. Dijkstra algorithm is single-source shortest path problem, as you mentioned in the article.
Other implementation problem. Algorithm complexity in your implementation is O(N^4) and Dijkstra algorithm is O(N^3). N - number of nodes. Would you mind considering correction of the function ExistEdge. In my opinion it is the error because complexity of ExistEdge should be O(1), and currently is O(N^2).
Best regards, MCS - Discrete Optimization
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Yes, you are right! I admit that the code it isn't optimized. When I will get the time I will make those functions run faster.
Ciprian
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
I am really glad that someone finally brough subject of algorithms into the Code Project. When I needed a starting point on graph algorithms 6 month ago, I could not find anything. Thanks
|
| Sign In·View Thread·PermaLink | 4.00/5 (1 vote) |
|
|
|
 |
|
|
I'm getting an error on loading the program that says "an unsupported operation was attempted!"
what does this mean? what do i have to do?
plz reply as soon as possible
|
| Sign In·View Thread·PermaLink | 2.00/5 (2 votes) |
|
|
|
 |
|
|
You must first register the dll or compile it!
project manager Solid understanding of Microsoft technologies: Windows ActiveX, COM / DCOM and ATL, SDK, STL, WTL, MFC
|
| Sign In·View Thread·PermaLink | 2.00/5 (2 votes) |
|
|
|
 |
|
|
A quick description on how to use the program (intuitvely unrelated to the Dijkstra Algorithm) would be useful for those not wishing to figure how to use the example but would like to see the logic in action.
|
| Sign In·View Thread·PermaLink | 2.00/5 (5 votes) |
|
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|