13,250,883 members (51,423 online)
alternative version

#### Stats

313.3K views
100 bookmarked
Posted 23 Dec 2003

# Dijkstra Algorithm

, 23 Dec 2003
 Rate this:
Shortest path (Dijkstra's Algorithm)

## 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 code

The 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()
{
}

{
}

void CAlgorithmsView::OnShortestPath()
{
CShorthestPath dlg;
if(dlg.DoModal()==IDOK)
/* dialog to take 2 longs which means the path*/
{
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 Implementation

```class CGraph
{
public:
long GetNrNodes();
CGraph();
virtual ~CGraph();
VTYPE_NODE m_nodes; // array of nodes
VTYPE_EDGE m_edges; // array of edges
VTYPE_NODE_P d; // array of longs that contain
// the shortest path at every step
VTYPE_NODE_P pi; // array of longs that contain
// the predecessor of each node for the shortest path
};```
```class CNode
{
public:
CNode Copy();
double m_cost; // not used yet
long m_NodeNr; // node number
POINT m_p; // graphical point for that node
CNode();
virtual ~CNode();
};```
```class CEdge
{
public:
bool m_red; // used to draw the result
// (if an edge it is a part of the shortest path it is drawn in red)
double m_cost; // the cost of an edge (picked randomly between 0-9)
long m_secondNode; // the second node number
long m_firstNode; // the first node number
POINT m_secondPct; // graphical elements for drawing the edges
POINT m_firstPct;
CEdge();
virtual ~CEdge();
};
// the graph is oriented from the first node to the second node```

## The Dijkstra's Algorithm (Implementation)

```// The Dijkstra's algorithm
STDMETHODIMP CDijkstra::ShortestPath(long node1, long node2)
{
ReleaseGraph();
// init d and pi
InitializeSource(g, g.m_nodes[node1-1]);
// Set S empty
VTYPE_NODE S;
// Put nodes in Q
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);
}
// Algorithm
while(Q.size())
{
CNode nod = ExtractMin(Q); // the minim value for
// the shortest path up to this step
S.push_back(nod);
// each vertex v which is a neighbour of u
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;
}```

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

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

## About the Author

 Web Developer Romania
Education Computer Engineering Faculty 1994-1999
University of Iasi ? Romania
Engineering degree: system and computers
Specialty: programmer analyst
License: (Computer Engineering Faculty) 2000
Master: (Distributed Computing) 2001 - 2002
Final Project: Remote Access. Encrypted file transfer.
Accessing any computer?s desktop through Internet or LAN.
Technologies: COM, ATL, API, SDK, MFC

## Comments and Discussions

 View All Threads First Prev Next
 Interestingly, you can often do *much* better than Dijkstra! Don Clugston4-Jan-04 14:35 Don Clugston 4-Jan-04 14:35
 Re: Interestingly, you can often do *much* better than Dijkstra! kozlowski22-Jan-04 15:15 kozlowski 22-Jan-04 15:15
 Re: Interestingly, you can often do *much* better than Dijkstra! Don Clugston28-Jan-04 19:17 Don Clugston 28-Jan-04 19:17
 >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.
 Re: Interestingly, you can often do *much* better than Dijkstra! kackermann30-Jul-06 17:37 kackermann 30-Jul-06 17:37
 Last Visit: 31-Dec-99 19:00     Last Update: 20-Nov-17 1:48 Refresh 1

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.