You are on page 1of 14

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

Ms

Siguiente blog

Crear blog
Acceder

Programming Techniques
Tutorials and Mini Projects of C, C++, PHP, OpenGL, and other languages with C/C++ codes of Data Structure, Numerical Methods and
Computer Graphics
Home

C Projects

C++ Projects

Computer Graphics

Data Structure

GLUT Tutorial

Numerical Methods

Monday, January 30, 2012

Image Processing

49

Implementation of Dijkstras Shortest Path Algorithm in C++


Topics
Advanced C Tutorial
(18)
Android Application Development
(7)
Artificial Intelligence
(4)
Assembly Tutorials
(3)
Business Intelligence
(1)
C Projects
(7)
C Tutorial
(40)
Computer Graphics
(13)
cplusplus projects
(6)
Cplusplus Tutorial
(34)

Dijkstras Shortest Path Algorithm is popular algorithm for finding shortest path between different nodes.

Data Analysis
(1)

The algorithm (Pseudo Code) is as follows

Data Structure and Algorithm


(26)

procedure Dijkstra (G): weighted connected simple graph,

with all weights positive)

[G has vertices a = v0, v1, ..... , vn = z and weights w(v1, v2)


where w(vi, vj) = INFINITY if [vi, vj] is not an edge in G]

Database
(1)

Loading [MathJax]/extensions/TeX/AMSsymbols.js

for i := 1 to n

L(vi) := INFINITY

L(a) := 0

S := NULL

[ the labels are now initialized so that the label of a is 0

and all other labels are INIFINITY, S is empty set]


while z is not belongs to S

begin

u := a vertex not in S with L(u) minimal


Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

GLUT Tutorial
(16)
Graphics Libraries
(4)
Image Processing
(12)
Javascript Tutorial
(2)
Linux
(3)
Machine Learning
(3)
Numerical Methods
(20)
PHP Tutorial
(13)

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

S := S U [u]
for all vertices u not in S

If L(u) + w(u,v) < L(v) then L(v) := L(u) + w(u,v)

[this adds a vertex to S with minimal label and updates the labels

vertices no in S]

end [L(z) = length of a shortest path from a to z]

PROLOG
(8)
R
(1)

Find us on Facebook

Example:
Popular Posts

Now lets come to an example which further illustrates above algorithm. Consider a weighted graph

Top Collections(Lists) of Mini Projects in C


and C++ free download source code and
exe.
Here are the collections of Mini Projects in
c and c++ with full source code and
executable file. All the codes are compiled
using GCC Com...

Breadth First Search in C++


Algorithm and Source Code
Basic Theory Breadth first
searches are performed by
exploring all nodes at a given
depth before proceeding to
the next level. This means...

Google Cloud Messaging


(GCM) in Android using PHP
Server
GCM for android is a service
which is basically used to
send the data from server to
the android devices. One use of this GCM is
a push noti...

Here a, b, c .. are nodes of the graph and the number between nodes are weights (distances) of the
graph. Now we are going to find the shortest path between source (a) and remaining vertices. The
adjacency matrix of the graph is

Depth First Search in C++


Algorithm and Source Code
Basic Theory Depth first
searches are performed by
diving downward into a tree
as quickly as possible. It does
this by always generatin...

Transformation (Translation,
Rotation and Scaling) of a two
dimensional objects in C/C++
1. Translation A translation is
applied to an object by
repositioning it along a
straight-line path from one coordinate
location to anot...

Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

Mini project Employee record


system using C
The employee record system
is very simple and for very
beginner mini project. It is
based one the menu-driven
program for elementary datab...

Now the following source code implements the above example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

#include<iostream>
#define INFINITY 999

using namespace std;

class Dijkstra{
private:
int adjMatrix[15][15];
int predecessor[15],distance[15];
bool mark[15]; //keep track of visited node
int source;
int numOfVertices;
public:
/*
* Function read() reads No of vertices, Adjacency Matrix and source
* Matrix from the user. The number of vertices must be greather than
* zero, all members of Adjacency Matrix must be postive as distances
* are always positive. The source vertex must also be positive from 0
* to noOfVertices - 1

*/
void read();

/*
* Function initialize initializes all the data members at the begining
of
* the execution. The distance between source to source is zero and all

Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

C Mini Project Ideas with a Sample


Calculator Project
Do you want to build a simple application
in C but you dont know how and where to
start? Or you know how to build a C
application but don...
Difference between Arrays and Structures
in C
Both the arrays and structures are
classified as structured data types as they
provide a mechanism that enable us to
access and manipulate...

Mini project Calendar


Application Using C/C++
Free download.
Mini project Calendar
Application is also a simple
project made using C. It uses
many windows properties to make it
colorful, for exampl...

Mini Project Student Record


System in C
Mini project student record
system is another project
based on programming
language C. It also uses files

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

other
* distances between source and vertices are infinity. The mark is
initialized
* to false and predecessor is initialized to -1
*/

void initialize();

/*
* Function getClosestUnmarkedNode returns the node which is nearest
from the
* Predecessor marked node. If the node is already marked as visited,
then it search
* for another node.
*/

int getClosestUnmarkedNode();
/*
* Function calculateDistance calculates the minimum distances from the
source node to
* Other node.
*/

void calculateDistance();
/*
* Function output prints the results
*/

void output();
void printPath(int);
};

void Dijkstra::read(){
cout<<"Enter the number of vertices of the graph(should be > 0)\n";
cin>>numOfVertices;
while(numOfVertices <= 0) {
cout<<"Enter the number of vertices of the graph(should be >
0)\n";
cin>>numOfVertices;
}
cout<<"Enter the adjacency matrix for the graph\n";
cout<<"To enter infinity enter "<<INFINITY<<endl;
for(int i=0;i<numOfVertices;i++) {
cout<<"Enter the (+ve)weights for the row "<<i<<endl;
for(int j=0;j<numOfVertices;j++) {
cin>>adjMatrix[i][j];
while(adjMatrix[i][j]<0) {
cout<<"Weights should be +ve. Enter the weight again\n";
cin>>adjMatrix[i][j];
}
}
}
cout<<"Enter the source vertex\n";

Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

as database. This project is sim...

Blog Archive

2014
(2)

2013
(27)

2012
(74)

November
(1)

October
(1)

July
(5)

June
(8)

May
(8)

April
(4)

March
(10)

February
(17)

January
(20)
Finding 1s Complement of a Binary
Number is C
Implementation of Dijkstras Shortest
Path Algorit...
Transformation (Translation, Rotation
and Scaling)...
Random number generation in C/C++
New Standard Flowchart of for loop.
Mini project Database Management
System (DBMS) usi...
GLUT Tutorial How to detect a Mouse
Click and Mo...
Drawing an Ellipse with Mid Point
Ellipse Algorith...
Drawing a Circle with Mid Point Circle
Algorithm...
How to do Texture Mapping in
OpenGL?? A sample e...
Numerical Method: Newtons Forward
and Backward In...
Implementing Bresenhams Line
Drawing Algorithm in...

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

cin>>source;
while((source<0) && (source>numOfVertices-1)) {
cout<<"Source vertex should be between 0 and"<<numOfVertices1<<endl;
cout<<"Enter the source vertex again\n";
cin>>source;
}
}

void Dijkstra::initialize(){
for(int i=0;i<numOfVertices;i++) {
mark[i] = false;
predecessor[i] = -1;
distance[i] = INFINITY;
}
distance[source]= 0;
}

int Dijkstra::getClosestUnmarkedNode(){
int minDistance = INFINITY;
int closestUnmarkedNode;
for(int i=0;i<numOfVertices;i++) {
if((!mark[i]) && ( minDistance >= distance[i])) {
minDistance = distance[i];
closestUnmarkedNode = i;
}
}
return closestUnmarkedNode;
}

void Dijkstra::calculateDistance(){
initialize();
int minDistance = INFINITY;
int closestUnmarkedNode;
int count = 0;
while(count < numOfVertices) {
closestUnmarkedNode = getClosestUnmarkedNode();
mark[closestUnmarkedNode] = true;
for(int i=0;i<numOfVertices;i++) {
if((!mark[i]) && (adjMatrix[closestUnmarkedNode][i]>0) ) {
if(distance[i] >
distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i]) {
distance[i] =
distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i];
predecessor[i] = closestUnmarkedNode;
}
}
}
count++;
}
}

Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

Drawing Straight Line using DDA


Algorithm in C/C++...
SetPixel() function on windows.h . How
to use it??...
Game project Tank Game using C++
with Allegro. S...
GLUT Tutorial Handling Keyboard
Events
Some Lab assignments on 8086
programming I
Android Why Google map is not
displayed in my ap...
Android - How to obtain Google API key
for Windows...
I am planning to develop an Android
Application in...

2011
(128)

Search This Blog


Loading...

Followers

Flag Counter

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

void Dijkstra::printPath(int node){


if(node == source)
cout<<(char)(node + 97)<<"..";
else if(predecessor[node] == -1)
cout<<"No path from <<source<<to "<<(char)(node + 97)<<endl;
else {
printPath(predecessor[node]);
cout<<(char) (node + 97)<<"..";
}
}

void Dijkstra::output(){
for(int i=0;i<numOfVertices;i++) {
if(i == source)
cout<<(char)(source + 97)<<".."<<source;
else
printPath(i);
cout<<"->"<<distance[i]<<endl;
}
}

int main(){
Dijkstra G;
G.read();
G.calculateDistance();
G.output();
return 0;
}

The output of above program is

Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

Free counters

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

About Author

Bibek Subedi is a computer engineering gratuate and founder of Programing


Techniques. He loves researching in the field of Machine learning, data mining
and Algorithms. He is a part time blogger, a bathroom singer (:D) and an
employer of a software company. You can follow him in Twitter and find him in
Facebook or mail him

Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

31 comments:
N Raz January 10, 2013 at 7:30 PM
Thank you. Love the way you have put comments to explain as to what are you up too. Thank you and keep
posting codes with comments. They really help
Reply

Anonymous February 10, 2013 at 8:32 PM


Great work. Clear, concise code. Thank you
Reply

zawmyohtet March 18, 2013 at 11:50 AM


Thank you.It helps me a lot.
Reply

zawmyohtet March 18, 2013 at 11:52 AM


May I asked you to post Bellman-Ford algorithm like this one.
Reply
Replies

Bibek Subedi

March 18, 2013 at 4:20 PM

Ok i will post it after my exam :):)


Reply

Henning Reich April 2, 2013 at 8:28 PM


Thank You, but is it possible to get multiple shortest paths?
Reply
Replies

Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

Bibek Subedi

April 3, 2013 at 7:53 AM

Yep, there may be multiple shortest path between any two nodes. But above code only shows a
single shortest path.
Reply

Patrick Korona April 9, 2013 at 1:44 AM


How would you impliment this code by reading in a file formatted like this:
1 2 10
1 4 30
1 5 100
2 3 50
2 1 70
3 5 10
3 1 50
4 3 20
4 5 60
5 2 40
Q
the numbers (1-5) are the vertices and the third number in the line is the weight. the file length will be
unspecified and Q terminates the file? Your code helps but im not sure how to convert to get this file
format to work
Reply

Anonymous June 11, 2013 at 1:30 AM


Thanks ! great work and keep going, it was really helpful ;)
Reply

Anonymous June 24, 2013 at 2:58 PM


hey i am using turbo c and getting lot of errors in the program ..which one do you think is the best compiler
to run this progam
Reply
Replies

Bibek Subedi

June 24, 2013 at 6:15 PM

Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

This code may not work in Turbo C. This is compiled using GCC MinGW Compiler.

Anonymous June 25, 2013 at 3:11 PM


thank you so much for your valuable reply Bibek..if you dont mind could you please tell me step
by step instructions to run this program using GCC MinGW compiler. i am not able to do that
please its a request

Bibek Subedi

June 25, 2013 at 3:52 PM

Download
the
Code::Blocks
binary
from
this
link
http://prdownload.berlios.de/codeblocks/codeblocks-12.11mingw-setup_user.exe. The GCC
compiler is already embedded with this so just run the code and you will see the output
Reply

Anonymous June 26, 2013 at 7:45 AM


thank you so much!! everything is working fine :) out of many other programs which i downloaded this is
one giving the exact output as i wanted...happyyyyyyy:) :)
Reply
Replies

Bibek Subedi

June 26, 2013 at 11:13 AM

Glad to hear that. This program actually uses Adjacency matrix. you can modify it to entire a
entire graph instead of matrix. If you find any bug then let me know

@mit@ July 11, 2015 at 6:44 PM


Thanks for the code! :) could you explain how you would modify a graph to use this algorithm?
Reply

ROHIT CHOUDHARY July 21, 2013 at 5:26 AM


thanks for program . God bless you , should i prefer using priority queue instead ?
Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

Reply
Replies

Bibek Subedi

July 21, 2013 at 7:20 AM

Yes Rohit you can use priority queue. Priority queue makes the program even faster
Reply

Preethi S July 30, 2013 at 6:58 AM


Hi Bibek,
I am trying to implement Dijkstra's algorithm in C with the help of your code above. I tried the same but
somehow I am not able to get the expected shortest path.
The modifications I have made are:
Instead of asking user input for the number of nodes and cost, I am giving an input file which has all these
info. I also mention the source and destination node from which I want the code to find the shortest path.
But somehow everytime it just says no path from "source" to "destination"
Will you be able to help me with this?
Thanks in advance for any help.
-Preethi
Reply
Replies

Bibek Subedi

July 30, 2013 at 9:34 AM

Hello Preethi, please send me your code at subedishankar2011@gmail.com. I will look at it and
provide you the feedback. Thanks
Reply

Preethi S July 31, 2013 at 1:41 AM


Hi Bibek,
I have mailed you my source files. Please do have a look at it.
Thanks
Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

Reply

Anonymous October 30, 2013 at 1:52 PM


i am not able to run the above source code in dev c++ compiler.I got struck at line no 109.please help me
Reply
Replies

Bibek Subedi

October 30, 2013 at 2:10 PM

Can you show me the error you got ?


Reply

Anonymous October 31, 2013 at 9:58 AM


Error:no'int Dijstra::getclosestUnmarkedNode()' member function declared in dijkstra
In member function'void Dijkstra::calculate Distance()'
Reply

Anonymous November 4, 2013 at 1:33 PM


please help me to rectify this error
Reply
Replies

Naqqash Naeem May 14, 2014 at 2:02 PM


bro there are errors of spaces there in the program
press backspace and then tab then the errors will be corrected
Reply

Harshitha R March 24, 2014 at 4:34 PM


pl provide opengl source code for djkstarts
Reply
Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

Harshitha R March 24, 2014 at 4:39 PM


pl providr source code for dijkstarts
Reply

Dev Narayan May 24, 2014 at 12:45 PM


Nice and simple implementation. Nice job.
But isn't the complexity n^2 instead of (m+n)logn?
Reply

DEEP BISWAS August 16, 2014 at 1:33 AM


This algorithm is not dijkstra because no heap is maintained
Reply

cheikh drame December 22, 2014 at 8:14 AM


this would not work if it has a cycle. explain..d
Reply
Add comment

Account
Google Account
Comment as:
Google

Publish

Preview

Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

Implementation of Dijkstras Shortest Path Algorithm in C++ | Programming Techniques

Newer Post

Home

Older Post

Subscribe to:
Post Comments (Atom)

View My Stats

Bibek Subedi. Powered by Blogger.

Implementation of Dijkstras Shortest Path Algorithm in C++ _ Programming Techniques.html[17/09/2015 01:47:01 p. m.]

You might also like