0% found this document useful (0 votes)
40 views

Description of The Algorithm

This summary provides an overview of Dijkstra's algorithm for finding the shortest path between nodes in a graph: Dijkstra's algorithm finds the shortest path from a source node to all other nodes in a graph. It works by assigning tentative distances to nodes and updating them until it finds the actual shortest paths. The algorithm uses priority queues and greedy choices to first explore the closest nodes, building up paths towards more distant ones.

Uploaded by

012362
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Description of The Algorithm

This summary provides an overview of Dijkstra's algorithm for finding the shortest path between nodes in a graph: Dijkstra's algorithm finds the shortest path from a source node to all other nodes in a graph. It works by assigning tentative distances to nodes and updating them until it finds the actual shortest paths. The algorithm uses priority queues and greedy choices to first explore the closest nodes, building up paths towards more distant ones.

Uploaded by

012362
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 19

Description of the Algorithm

In this paper we are interested to describe Djikstra's


algorithm for finding the shortest path from one source city
to all other cities in a graph. 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 problem

Lets take the nodes one(1) and twelve(12).There are paths


(1 _10_11_12 and 1_8_9_10_11_12) but the shortest of them
is 1 _10_11_12 of length 80KM.our job is to find this one
using the Dijkstra’s Algorithm

The Algorithm
Dijkstra’s algorithm is one of the most common solutions
for this problem. Even so, it only works on graphs which
have no edge of negative weight, and the actual speed of
the algorithm can vary from O(n*lg(lg (n))) to O(n2)

Course project on Analysis of Algorithm


1 of 19
Now let’s see the use of each function used to perform this
algorithm

Create_Graph() function
This function will create the adjacency matrix by reading the
distance of each node from previously stored a route
distance in RouteDist.txt from source city to destination
city .And also is used to save the color of each node to green
in an array format to show the nodes are not yet used in the
algorithm.

1 2 3 4 5 6 7 8 9 10 11 12
0 0 0 0 0 0 0 0 0 0 0 0

Array Colour: zero is GREEN

Initialize () function
Because of the Create_Graph function, we do have the
Graph and now we already know that the graph has no
edges of negative weight, here the function will set the
length of the shortest path to all cities (nodes) to
Big(Infinity),the length of the shortest path to the source as
zero(0) in the distance storage array dist

1 2 3 4 5 6 7 8 9
10 11 12
0 99 99 99 99 99 99 99 99 99 99 99
99 99 99 99 99 99 99 99 99 99 99

Array dist: zero is source and 9999 to indicate Infinity

Course project on Analysis of Algorithm


2 of 19
And as well using this function we set the predecessor of
each node to array pred from the given Adjacency matrix
AdjMatrix[i][j]

1 2 3 4 5 6 7 8 9 10 11 12
0 1 0 0 0 0 1 1 0 1 0 0

Array Pred: here 2,7,8,10 are predecessor of


node 1

RunSortestPath() function
This function is the main working function of Dijkstra’s
Algorithm in which all the functions used are called from this
function (Create_Graph,Initiaklize,Update). In this function
we use two variables flg,and p
• Flg Variable-this variable lets us to check
whether the task on a given node is completed or not
using the array colour .i.e,checks the value on array
colour of the given node is whether red(value 2) or
not
• P variable –this variable is used to label the
minimum edge distance to YELLOW(value 1) ,i.e. the
node(city) edge is selected as shortest path to reach
to destination node(city)

Get_Min_Distance() function
The use of this function is to label the node (city) to YELLOW
with the minimum edge distance from the source to the
wanted destination node(city) and return the position ‘P’ on
which the colour of the edge to be changed to YELLOW on
array colour.

Update () function

Here this function is used to update the min distance for the
YELLOW coloured edge and modify the predecessor of the
destination with the one shortest distance to it.

Course project on Analysis of Algorithm


3 of 19
The following functions will not be discussed in detail; any
body can suggest from their name the need of each function
and are ordinary functions we know from previous c++
program(how to use menu driven program and inserting
data to file ,display data from a file to screen)
• Main_Menu();
• Insert_Data_Menu();
• Insert_Truck();
• Insert_City();
• Insert_Route_Distance();
• search_at_CTY();
• Display_Info_Menu();
• Display_Location(Truck& t);
• Display_By_Plate();
• Display_By_Name();
• print_Header();

and we also have


• class shortestpath to declare all functions and
variables that are used to find the shortest path to all
cities having a source city in the Dijkstra’s algorithm
• Struct Truck used to hold the variables necessary for
truck information
• Struct City used to hold the variables necessary for
city information

Course project on Analysis of Algorithm


4 of 19
Implementation Code for the project
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <stdlib.h>
#include <iomanip.h>
#include <string.h>
#include <stdio.h>
#define MAX 20
#define Big 9999

struct Truck{

char pNumber[10];
char dName[15];
char dId[10];
char cStation[10];
float tMileAge;
char npRoute[15];
};

struct City {
char cName[10];
int sNumber;
};

class ShortestPath{

Course project on Analysis of Algorithm


5 of 19
private:
int n;
int AdjMatrix[MAX][MAX];
int colour[MAX];
int sCTY;
int dist[MAX];
int pred[MAX];
enum {GREEN,YELLOW,RED};
public:
void Create_Graph();
void Initialize();
int Get_Min_Distance();
void UPDATE(int);
void DisplayPath();
void RunShortestPath();
};

int Main_Menu();
void Insert_Data_Menu();
void Insert_Truck();
void Insert_City();
void Insert_Route_Distance();
void search_at_CTY();

void Display_Info_Menu();
void Display_Location(Truck& t);
void Display_By_Plate();
void Display_By_Name();

void print_Header();

void main(void){

clrscr();
int choice = 0;

while ((choice = Main_Menu())!=5)


{
switch (choice)
{
case 1:Insert_Data_Menu();break;
case 2:Display_Info_Menu();break;

Course project on Analysis of Algorithm


6 of 19
case 3:
ShortestPath sPath;
sPath.RunShortestPath();break;
case 4:search_at_CTY();break;
case 5:exit(1);
default:cout<<"Invalid choice...!\n\n";break;
}
}
} // main

int Main_Menu(void)
{
int choice;
cout<<"\n\t # # # # # # # # ##### # # # # ";
cout<<"\n\tzzzzz ## ## # # # ## # ## ## # ## # # # zzzzz";
cout<<"\n\tzzzzz # # # ##### # # # # # # # #### # # # # # zzzzz";
cout<<"\n\tzzzzz # # # # # # ## # # # # ## # # zzzzz";
cout<<"\n\t # # # # # # # # # ##### # # ### \n\n\n";
cout<<"\n\t\t+-----------------------------------------------+";
cout<<"\n\t\t| 1. Insert new data |";
cout<<"\n\t\t| |";
cout<<"\n\t\t| 2. Display Information |";
cout<<"\n\t\t| |";
cout<<"\n\t\t| 3. Calculate shortest path |";
cout<<"\n\t\t| |";
cout<<"\n\t\t| 4. Search Truck with lowest mile age at CTY |";
cout<<"\n\t\t| |";
cout<<"\n\t\t| 5. Exit |";
cout<<"\n\t\t+-----------------------------------------------+";
cout<<"\n\n\nPlease enter your choice : ";
cin>>choice;

return choice;
} // Main_Menu

void Insert_Data_Menu(){
int choice;
do{
cout<<"\n\t # # # #### #### #### ##### #### # ##### # ";
cout<<"\n\tzzzzz # ## # # # # # # # # # # # # # zzzzz";
cout<<"\n\tzzzzz # # # # ### #### # # # # # ##### # ##### zzzzz";
cout<<"\n\tzzzzz # # ## # # # # # # # # # # # # zzzzz";

Course project on Analysis of Algorithm


7 of 19
cout<<"\n\t # # # #### #### # # # #### # # # # # \n";
cout<<"\n\t\t+-----------------------------------------------+";
cout<<"\n\t\t| 1. Insert new Truck info |";
cout<<"\n\t\t| |";
cout<<"\n\t\t| 2. Insert new city Info |";
cout<<"\n\t\t| |";
cout<<"\n\t\t| 3. Insert Route Distance |";
cout<<"\n\t\t| |";
cout<<"\n\t\t| 4. Back to Main Menu |";
cout<<"\n\t\t| |";
cout<<"\n\t\t+-----------------------------------------------+";
cout<<"\n\nPlease enter your choice : ";
cin>>choice;
switch (choice){
case 1:Insert_Truck();break;
case 2:Insert_City();break;
case 3:Insert_Route_Distance();break;
case 4:break;
default:cout<<"Invalid Choice\n";break;
}
} while(choice != 4);

}//Insert_data_Menu

void Insert_Truck(){

fstream tFile("c:\\truck.txt",ios::app|ios::in|ios::out);
char ch;
Truck t;

do{
cout<<"Enter Plate Number:";
cin>>t.pNumber;
cout<<"Enter driver name : ";
cin>>t.dName;
cout<<"Enter driver ID : ";
cin>>t.dId;
cout<<"Enter current station : ";
cin>>t.cStation;
cout<<"Enter total mile Age : ";
cin>>t.tMileAge;
cout<<"Enter next planned route : ";
cin>>t.npRoute;
tFile.write((char *)&t,sizeof(t));
cout<<"\nWant to add more truck info?(y/n)\n";
cin>>ch;
} while (ch=='y' || ch=='Y');
tFile.close();
} // Insert_Truck

void Insert_City(){
Course project on Analysis of Algorithm
8 of 19
fstream cFile("c:\\city.txt",ios::in|ios::out|ios::app);
char ch;
City city_rec;

do{
cout<<"Enter city name:";
cin>>city_rec.cName;
cout<<"Enter city station Number : ";
cin>>city_rec.sNumber;
cFile.write((char *)&city_rec,sizeof(city_rec));
cout<<"\nWant to add more city info?(y\n)\n";
cin>>ch;
} while (ch=='y' || ch=='Y');

} // Insert_City

void Insert_Route_Distance(){

float dis;
clrscr();

float file[MAX][MAX];
fstream tFile("c:\\RouteDis.txt",ios::in|ios::out);
cout<<"\nEnter Distance node if they are connected, otherwise
zero\n\n\n";
for(int i=1;i<=12;i++){
for(int j=1;j<=12;j++){
cout<<"Enter Distance station:"<<i<<"->"<<j<<":";
cin>>dis;
tFile<<dis<<" ";
}
}
tFile.close();

}//Insert_Route_Distance

void Display_Info_Menu(){
int choice;
Truck t;
do{
cout<<"\n #### # #### ### # # # # # # #### # # # # ";
cout<<"\nzzzzz # # # # # # # # # # # ## ## # ## # # # zzzzz";
cout<<"\nzzzzz # # # ### ### # ##### # # # # #### # # # # # zzzzz";
cout<<"\nzzzzz # # # # # # # # # # # # # ## # # zzzzz";
cout<<"\n #### # #### # #### # # # # # #### # # ### \n";

Course project on Analysis of Algorithm


9 of 19
cout<<"\n\t+---------------------------------------------------------+";
cout<<"\n\t | 1. Display the location of each truck |";
cout<<"\n\t| |";
cout<<"\n\t| 2. Display truck detail ordered by their plate number |";
cout<<"\n\t| |";
cout<<"\n\t| 3. Display truck detail ordered by their driver name |";
cout<<"\n\t| |";
cout<<"\n\t| 4. Back to Main Menu |";
cout<<"\n\t| |";
cout<<"\n\t+---------------------------------------------------------+";
cout<<"\n\nPlease enter your choice : ";
cin>>choice;
switch (choice){
case 1:Display_Location(t);break;
case 2:Display_By_Plate();break;
case 3:Display_By_Name();break;
case 4:break;
default:cout<<"Invalid Choice\n";break;
}
} while(choice != 4);

}//Display_Info_Menu

void Display_Location(Truck& t){

fstream tFile("c:\\truck.txt",ios::in|ios::out);

if(!tFile){
cout<<"Error in Opening Truck File....Program End\n";
exit(1);
}
else{

tFile.seekg(0);
tFile.read((char*)&t,sizeof(t));
cout<<endl;
print_Header();
while(!tFile.eof()){
cout<<setw(10)<<setfill(' ')<<t.pNumber;
cout<<setw(10)<<setfill(' ')<<t.cStation;
cout<<setw(10)<<setfill(' ')<<t.tMileAge<<endl;
tFile.read((char*)&t,sizeof(t));

}
}
cout<<"\n------------+----------+--------------+\n";
tFile.close();
}//Display_Location

Course project on Analysis of Algorithm


10 of 19
void Display_By_Name(){

Truck Truck_rec[20];
int i=0;
fstream tFile("c:\\truck.txt",ios::in|ios::out);

if (!tFile) {
printf("Error in Opening files... Program End\n");
getch();
exit(1);
}

tFile.seekg(0);
tFile.read((char*)&Truck_rec[i],sizeof(Truck));

while(!tFile.eof()){
tFile.read((char*)&Truck_rec[i],sizeof(Truck));
i++;
}

tFile.close();

int j, k;

int n=i;

// Sort all records by name


for(j=0;j<n;j++)
{
for(k=n-1;k>j;k--)
{
if(strcmp(Truck_rec[k].dName, Truck_rec[k-
1].dName)<0){
Truck temp;
temp = Truck_rec[k];
Truck_rec[k] = Truck_rec[k-1];
Truck_rec[k-1] = temp;
}
}
}

// Print all records

Course project on Analysis of Algorithm


11 of 19
cout<<setw(10)<<setfill(' ')<<"PlateNo"<<setw(10)<<setfill('
')<<"DName"<<setw(6)<<setfill(' ')<<"DID";
cout<<setw(11)<<setfill(' ')<<"CurStat"<<setw(9)<<setfill(' ')<<"MileAge";
cout<<setw(12)<<setfill(' ')<<"next Route";
cout<<"\n+----------------------------------------------------------+\n";
for(j=0;j<n;j++){
cout<<endl;
cout<<setw(8)<<setfill(' ')<<Truck_rec[j].pNumber;
cout<<setw(10)<<setfill(' ')<<Truck_rec[j].dName;
cout<<setw(8)<<setfill(' ')<<Truck_rec[j].dId;
cout<<setw(8)<<setfill(' ')<<Truck_rec[j].cStation
cout<<setw(8)<<setfill(' ')<<Truck_rec[j].tMileAge;
cout<<setw(15)<<setfill(' ')<<Truck_rec[j].npRoute;
}

cout<<"\n+----------------------------------------------------------+\n\n";
cout<<"\nPress any key to continue";
getch();

}// Display_by_Name

void Display_By_Plate(){

Truck Truck_rec[20];
int i=0;
fstream tFile("c:\\truck.txt",ios::in|ios::out);

if (!tFile) {
printf("Error in Opening files... Program End\n");
getch();
exit(1);
}

tFile.seekg(0);
tFile.read((char*)&Truck_rec[i],sizeof(Truck));

while(!tFile.eof()){
tFile.read((char*)&Truck_rec[i],sizeof(Truck));
i++;
}

tFile.close();

int j, k;

int n=i;

Course project on Analysis of Algorithm


12 of 19
// Sort all records by plate
for(j=0;j<n;j++)
{
for(k=n-1;k>j;k--)
{
if(strcmp(Truck_rec[k].pNumber, Truck_rec[k-
1].pNumber)<0){
Truck temp;
temp = Truck_rec[k];
Truck_rec[k] = Truck_rec[k-1];
Truck_rec[k-1] = temp;
}
}
}

// Print all records


cout<<setw(10)<<setfill(' ')<<"PlateNo"<<setw(10)<<setfill('
')<<"DName"<<setw(6)<<setfill(' ')<<"DID";
cout<<setw(11)<<setfill(' ')<<"CurStat"<<setw(9)<<setfill(' ')<<"MileAge";
cout<<setw(12)<<setfill(' ')<<"next Route";
cout<<"\n+----------------------------------------------------------+\n";
for(j=0;j<n;j++){
cout<<endl;
cout<<setw(8)<<setfill(' ')<<Truck_rec[j].pNumber;
cout<<setw(10)<<setfill(' ')<<Truck_rec[j].dName;
cout<<setw(8)<<setfill(' ')<<Truck_rec[j].dId;
cout<<setw(8)<<setfill(' ')<<Truck_rec[j].cStation;
cout<<setw(8)<<setfill(' ')<<Truck_rec[j].tMileAge;
cout<<setw(15)<<setfill(' ')<<Truck_rec[j].npRoute;
}

cout<<"\n+----------------------------------------------------------+\n\n";
cout<<"\nPress any key to continue";
getch();

}// Display_By_Plate

void print_Header(){
cout<<"\n\n------------+----------+--------------+\n";
cout<<"Plate Number C_Station T_Mileage";
cout<<"\n ------------+----------+--------------+\n";
} // print_Header

Course project on Analysis of Algorithm


13 of 19
void search_at_CTY(){
char ch;
int loc=0;
do{
fstream file("c:\\Truck.txt",ios::out|ios::in);
Truck s;
char CTY[20];
char* truckPlate[15];
float mileAge[15];
int sResult=0;
int i=0;

if(!file){
cout<<"Error openning a file program End";
getch();
exit(1);
}

cout<<"\n choose the City at which the lowest mileage is to be


searched\n";
cin>>CTY;

file.seekg(0);

Course project on Analysis of Algorithm


14 of 19
file.read((char*)&s,sizeof(s));

while(!file.eof())
{
if(strcmp(CTY,s.cStation)==0)
{
sResult=1;
strcpy(truckPlate[i],s.pNumber);
mileAge[i]=s.tMileAge;
i++;
}
file.read((char*)&s,sizeof(s));
}

if(sResult){
int n=i-1;
char* plate;
long int min;
min=mileAge[0];
for(i=1;i<=n;i++){
if(mileAge[i]<min){
min=mileAge[i];
loc=i;
}
}
cout<<"\n+-------------------------------------------------------------+\n";
cout<<"\nThe truck with lowest mile age at city: "<<CTY<<" is:
\n";
cout<<"\n\t plate Number "<<truckPlate[loc];;
cout<<"\t Mileage "<<min;
cout<<"\n+-------------------------------------------------------------+\n";
}
else
cout<<"\n No Truck at city "<<CTY<<" Found";
cout<<"\nDo you want to continue? (y / n) ";
cin>>ch;
file.close();

} while (ch=='y' || ch=='Y');

}//search_at_CTY

void ShortestPath::Create_Graph(){

fstream RdFile("c:\\RouteDis.txt",ios::in|ios::out);

Course project on Analysis of Algorithm


15 of 19
float Rd;
int i,j;
int Dist[144];
n=12;
if(!RdFile){
cout<<"Error in Opening Truck File....Program End\n";
getch();
exit(1);
}
i=0;
while(RdFile>>Rd)
{
Dist[i]=Rd;
i++;
}
int k=0;
for(i=1;i<=n;i++) {
cout<<endl;
for(j=1;j<=n;j++){
AdjMatrix[i][j]=Dist[k];
k++;
}
}

RdFile.close();

for(i=1;i<=n;i++)
colour[i]=GREEN;

cout<<"Enter the source City:\n";


cout<<"1.Addis Ababa 5.Gonder 9.Arba Minch ";
cout<<"\n2.Debre Markos 6.Mekelle 10.Nazret " ;
cout<<"\n3.Bahirdar 7.Dese 11.Dire Dawa ";
cout<<"\n4.Debre Tabo 8.Jima 12.Harer\n";

cin>>sCTY;
}//Create_Graph

void ShortestPath::Initialize(){
for(int i=1;i<=n;i++){
if(i==sCTY)
dist[i]=0;
else
dist[i]=Big;
}

Course project on Analysis of Algorithm


16 of 19
for(int j=1;j<=n;j++){
if(AdjMatrix[sCTY][j]!=0)
pred[j]=sCTY;
else
pred[j]=0;
}
}// Initialize

int ShortestPath::Get_Min_Distance(){
int min=Big;
int p=0;
for(int i=1;i<=n;i++){
if(colour[i]==GREEN){
if(min>=dist[i]){
min=dist[i];
p=i;
}
}
}
return p;
}// Get_Min_Distance

void ShortestPath::UPDATE(int p){


for(int i=1;i<=n;i++){
if(colour[i]==GREEN){
if(AdjMatrix[p][i]!=0){
if(dist[i]>AdjMatrix[p][i]+dist[p]){
dist[i]=AdjMatrix[p][i]+dist[p];
pred[i]=p;
}
}
}
}
}// UPDATE

void ShortestPath::DisplayPath(){

cout<<"\nThe paths and distances are\n";

for(int i=1;i<=n;i++){
if(pred[i]==0 && i!=sCTY){
cout<<"path does not exists between"<<i<<" and the sCTY city
"<<sCTY<<endl;
exit(1);

Course project on Analysis of Algorithm


17 of 19
}
cout<<"\npath to city "<<i<<" is\t";
int j=i;
int array[MAX];
int l=0;
while(pred[j]!=0){
array[++l]=pred[j];
j=pred[j];
}
for(int k=l;k>=1;k--)
cout<<array[k]<<"->";
cout<<i<<"..."<<dist[i]<<"KM"<<endl;
}

}// DisplayPath

void ShortestPath::RunShortestPath(){
Create_Graph();
Initialize();
int flg=0;
int i;

for(i=1;i<=n;i++)
if(colour[i]!=RED)
flg=1;

while(flg){
int p=Get_Min_Distance();
colour[p]=YELLOW;
UPDATE(p);
colour[p]=RED;
flg=0;
for(i=1;i<=n;i++)
if(colour[i]!=RED)
flg=1;

Course project on Analysis of Algorithm


18 of 19
DisplayPath();

}// RunShortestPath

Course project on Analysis of Algorithm


19 of 19

You might also like