Click here to Skip to main content
15,039,359 members
Articles / Programming Languages / C++
Posted 23 Dec 2003


102 bookmarked

Dijkstra Algorithm

Rate me:
Please Sign up or sign in to vote.
4.43/5 (40 votes)
23 Dec 20033 min read
Shortest path (Dijkstra's Algorithm)
Image 1


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::OnAddEdge() 

void CAlgorithmsView::OnShortestPath() 
    CShorthestPath dlg;
/* 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 
    long GetNrNodes();
    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
    CNode Copy();
    double m_cost; // not used yet
    long m_NodeNr; // node number
    POINT m_p; // graphical point for that node
    virtual ~CNode();
class CEdge 
    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;
    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)
    // init d and pi
    InitializeSource(g, g.m_nodes[node1-1]);
    // Set S empty
    // Put nodes in Q
    VTYPE_NODE::iterator kl;
    for(kl=g.m_nodes.begin(); kl<g.m_nodes.end(); kl++)
        CNode node = (*kl).Copy();
    // Algorithm
        CNode nod = ExtractMin(Q); // the minim value for 
              // the shortest path up to this step
        // 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;
                    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:


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

QuestionThank you Pin
LiaoVictor22-Jan-14 15:10
MemberLiaoVictor22-Jan-14 15:10 
Generalhelp Pin
hano222222-Mar-10 7:29
Memberhano222222-Mar-10 7:29 
hi everybody

i need help in writing a code for Dijkstra’s algorithm to find
the least-cost paths in the network with node C as the source node.
Then, Construct a routing table based on the least-cost paths for node C.
Generalplease help me answering..... Pin
annei8-Oct-09 22:29
Memberannei8-Oct-09 22:29 
Questionhelp me plsss,,,, Pin
sumario25-Aug-08 20:21
Membersumario25-Aug-08 20:21 
GeneralImplementing a Timer Functionality Pin
David James16-Mar-08 5:16
MemberDavid James16-Mar-08 5:16 
QuestionQuestion about Dijkstra Algorithm Pin
wongyum11-Mar-08 16:11
Memberwongyum11-Mar-08 16:11 
QuestionHow to create Topology for road networks? Pin
Durga Prasad Dhulipudi7-Aug-07 5:28
MemberDurga Prasad Dhulipudi7-Aug-07 5:28 
GeneralHelp for Dijkstra's graph algo in C# Pin
Asshish4-Jul-07 18:43
MemberAsshish4-Jul-07 18:43 
GeneralQuestion Pin
averys24-May-07 3:22
Memberaverys24-May-07 3:22 
GeneralVB version of Dijkstra's Algorithm Pin
mergul21-Apr-06 13:00
Membermergul21-Apr-06 13:00 
AnswerRe: VB version of Dijkstra's Algorithm Pin
abhijitkolas8-Apr-07 18:57
Memberabhijitkolas8-Apr-07 18:57 
Generalcrash Pin
Karsten Schulz30-Jul-05 10:38
professionalKarsten Schulz30-Jul-05 10:38 
Generale bun Pin
gamitech15-Sep-04 1:46
Membergamitech15-Sep-04 1:46 
GeneralNeeded your kind attention Pin
Hammad Raza Kazmi3-Aug-04 21:57
sussHammad Raza Kazmi3-Aug-04 21:57 
GeneralGot Some Problems! Help Please! Pin
RinoMerc4-Jun-04 12:02
MemberRinoMerc4-Jun-04 12:02 
GeneralInterestingly, you can often do *much* better than Dijkstra! Pin
Don Clugston4-Jan-04 13:35
MemberDon Clugston4-Jan-04 13:35 
GeneralRe: Interestingly, you can often do *much* better than Dijkstra! Pin
kozlowski22-Jan-04 14:15
Memberkozlowski22-Jan-04 14:15 
GeneralRe: Interestingly, you can often do *much* better than Dijkstra! Pin
Don Clugston28-Jan-04 18:17
MemberDon Clugston28-Jan-04 18:17 
GeneralRe: Interestingly, you can often do *much* better than Dijkstra! Pin
kackermann30-Jul-06 16:37
Memberkackermann30-Jul-06 16:37 
GeneralStop condition Pin
kozlowski4-Jan-04 12:10
Memberkozlowski4-Jan-04 12:10 
GeneralRe: Stop condition Pin
lgciprian6-Jan-04 3:16
Memberlgciprian6-Jan-04 3:16 
GeneralRe: Stop condition Pin
kozlowski6-Jan-04 13:49
Memberkozlowski6-Jan-04 13:49 
GeneralRe: Stop condition Pin
lgciprian6-Jan-04 20:28
Memberlgciprian6-Jan-04 20:28 
GeneralRe: Stop condition Pin
xumepoc14-Sep-11 4:51
Memberxumepoc14-Sep-11 4:51 
GeneralJust a comment Pin
Anonymous31-Dec-03 18:41
MemberAnonymous31-Dec-03 18:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

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