Finding shortest path in a Graph

Page 1

THE UNIVERSITY OF DODOMA

College Of Informatics and Virtual Education

NAME: Makame, Makame H REGISTRATION No: T/UDOM/2010/00410 PROGRAM: B Sc. Computer and Information Security

ASSIGNMENT NO.4

COURSE NAME: Data Structure and Algorithms

COURSE CODE: CS 104 COUSE INSTRUCTOR: Masoud Masoud

Question: Write a program for a shortest path in a Graph

Tuesday, January 31, 2012


Program #include<conio.h> #include <iostream.h> class spath { int costmatx[8][8]; int r,s; int dist[8]; public: void read_graph(); void source_vertex(); void shpath(); void display(); }; void spath::read_graph() { int i,j,n; cout<<"\t Enter the number of vertex = "; cin>>n; cout<<"\t\n"; for(i=1;i<=r;i++) { for(j=1;j<=r;j++) { cout<<"\tEnter the cost from " << i <<" to "<< j<<"= "; cin>>costmatx[i][j]; Tuesday, January 31, 2012


cout<<endl; } } } void spath::source_vertex() { cout<<"\tEnter the source vertix = "; cin>>s; cout<<"Choose the shortest path from the following\n"; } void spath::shpath() { int mv,i; static int f[8]; f[s]=1; for(i=1;i<=r;i++) dist[i]=costmatx[s][i]; for(int k=1;k<=r;k++) { int min=1000; for(i=1;i<=r;i++) if((f[i]!=1) && (dist[i]<min)) { min=dist[i]; mv=i; } Tuesday, January 31, 2012


f[mv]=1; for(i=1;i<=r;i++)

if(

(f[i]!=1)&&(dist[mv]+costmatx[mv][i]<dist[i]))

dist[i]=dist[mv]+costmatx[mv][i]; } } void spath::display() { for(int i=1;i<=r;i++) cout<<"\

Ditance from "<<s<<" to "<<i<<" is

"<<dist[i]<<"\n"; } void main() { cout<<"\t\tFINDING THE SHORTEST PATH IN A GRAPH\n\n";

spath sp; clrscr(); sp.read_graph(); sp.source_vertex(); sp.shpath(); sp.display(); getch(); }

Tuesday, January 31, 2012


Output

Tuesday, January 31, 2012


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.