SlideShare a Scribd company logo
1 of 12
Download to read offline
Write C/C++ a program that inputs a weighted undirected graph and finds the shortest path
between two vertices using Dijkstra’s algorithm, using indices to order the branching. The
program should take three command-line arguments: the name of the graph file, followed by a
source vertex, followed by a destination vertex. It should output to standard output the vertices in
a shortest path in order, including both the source and destination vertices, as well as the total
weight of the path. You may assume that any input graphs will have no negative-weight edges. A
user should see something very similar to the following when invoking your program.
> ./dijkstra graph.txt 2 3
2 5 6 1 0 3
3.51
>
Graph.txt:
7 9 //Represents number of vertices and edges, respectively.
Solution
main.cpp
#include "Dij.h"
#include
/*---------------------------------------------------------
* Name: main
* Purpose: driver module for testing Dij.h
* Param: filename, source vertex id, destination vertex id
*---------------------------------------------------------*/
int main(int argc, char **argv)
{
string filename;
if ( 1 < argc ) filename.assign( argv[1] );
Graph testGraph; // create Graph object
//string filename = argv[1]; // get filename
testGraph.createGraph(filename); // populate Graph
int source; // source index
int destination; // destination index
// convert strings to integers
stringstream s1(argv[2]);
s1 >> source;
stringstream s2(argv[3]);
s2 >> destination;
// find the shortest path
testGraph.findPath(source,destination);
// print the shortest path
testGraph.outputPath();
std::cout << std::endl;
}
Dij.h
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "Vertex.h"
#define infinity DBL_MAX
using namespace std;
/*-----------------------------------------------------------
* Name: Graph
* Purpose: Represent a graph G{V,E} alongside implementation
* of Dijkstra's algorithm
*-----------------------------------------------------------*/
class Graph
{
public:
Graph();
~Graph();
void createGraph(std::string);
void findPath(int, int);
void outputPath();
void relaxVertex(Vertex*);
// set the vertex of which the shortest path is being found
void setDestination(Vertex* destination){mDestination = destination;}
// get the vertex of which the shortest path is being found
Vertex* getDestination(){return mDestination;}
// set the vertex that is the starting point of the search
void setSource(Vertex* source){mSource = source;}
// get the vertex that is the starting point of the search
Vertex* getSource(){return mSource;}
private:
std::vector mVertices; //vector of vertices
std::map mWeights; //table of shortest path weights
Vertex* mDestination; //destination vertex
Vertex* mSource; //source vertex
};
/*---------------------------------------------------------
* Name: Default Constructor
*---------------------------------------------------------*/
Graph::Graph()
{
mDestination = NULL;
mSource = NULL;
}
/*---------------------------------------------------------
* Name: Destructor
*---------------------------------------------------------*/
Graph::~Graph()
{
//Free memory
if(!mVertices.empty())
{
while(mVertices.size())
{
Vertex * vertex = mVertices.back();
delete vertex;
mVertices.pop_back();
}
}
}
/*----------------------------------------------------------
* Name: createGraph
* Purpose: parse text file and construct graph
* Param: string - name of file to parse
*----------------------------------------------------------*/
void Graph::createGraph(std::string filename)
{
std::ifstream myfile; // ifstream object for opening file
myfile.open(filename.c_str(), ios::in); // open file
// if file does not exist or failed to open, return
if(!myfile.is_open())
{
cout << "File failed to open" << endl;
return;
}
// get lines from file for parsing
for(std::string line; std::getline(myfile, line);)
{
std::istringstream ss(line);
int index, value; //first node and node pointed at
double weight; //edge weight betweeen first and second nodes
// Get values from stream
ss >> index;
ss >> value;
ss >> weight;
// Add vertex to vertices list if not present
if(!mWeights.count(index))
{
Vertex * vertex = new Vertex(index);
vertex->addEdge(value, weight);
mVertices.push_back(vertex);
mWeights[index] = vertex; //record vertex in weight map
vertex->setWeight(infinity); //intialize weight to infinity
}
// Otherwise the vertice is present - add another edge
else
{
(mWeights[index])->addEdge(value, weight);
}
// If vertex has no edges, add to graph
if(!mWeights.count(value))
{
Vertex * vertex = new Vertex(value);
mVertices.push_back(vertex);
mWeights[value] = vertex; //record vertex in weight map
vertex->setWeight(infinity); //initialize weight to infinity
}
}
// close the file
myfile.close();
}
/*------------------------------------------------------------
* Name: findPath
* Purpose: Implements Dijkstra's algorithm with minHeap
* Param: ID of source and destination vertices
*------------------------------------------------------------*/
void Graph::findPath(int source, int destination)
{
// lambda functor for comparing vertices
auto compare = [](Vertex*lhs,Vertex*rhs)
{
return lhs->getWeight() > rhs->getWeight();
};
// index to minimum weight vertex
int index = 0;
// if the source of destination does not exist, there is no path
if(mWeights.count(source) && mWeights.count(destination))
{
// initialize source vertex to weight of zero
(mWeights[source])->setWeight(0);
// heapify
std::make_heap(mVertices.begin(), mVertices.end(), compare);
// set source node
this->setSource(mWeights[source]);
// search the graph and update shortest paths
while(index+1 != mVertices.size())
{
Vertex * vertex = mVertices[index]; //vertex of min weight with edges to search
// shortest path found if it has correct id and has been updated
if(vertex->getId() == destination && vertex->getWeight() != infinity)
{
this->setDestination(vertex); //set the destination node
break;
}
// shortest path has not been found, relax edges
else
{
this->relaxVertex(vertex);
}
//Heapify everything apart from extracted value
index+=1;
std::make_heap(mVertices.begin() + index, mVertices.end(), compare);
}
}
}
/*--------------------------------------------------------------
* Name: relaxVertex
* Purpose: update total path weight of a vertex in the graph
* Param: vertex whose edges are being searched
*-------------------------------------------------------------*/
void Graph::relaxVertex(Vertex* vertex)
{
std::map* edges = vertex->getEdges();
// search edges of current min vertex
for(auto iter = edges->begin(); iter != edges->end(); iter++)
{
// if the edges have not been seen, update weight
if((mWeights[iter->first])->getWeight() == infinity)
{
// weight is updated to current path weight + edge weight
(mWeights[iter->first])->setWeight((mWeights[vertex->getId()])->getWeight() +
iter->second);
(mWeights[iter->first])->setParent(vertex);
}
// if the vertex has been updated already, compare current path
// if new path is now minimal, update path
else if((mWeights[iter->first])->getWeight() > iter->second +
(mWeights[vertex->getId()])->getWeight())
{
(mWeights[iter->first])->setWeight((mWeights[vertex->getId()])->getWeight() +
iter->second);
(mWeights[iter->first])->setParent(vertex);
}
}
}
/*-----------------------------------------------------------------
* Name: outputPath
* Purpose: output shortest path for destination node
*-----------------------------------------------------------------*/
void Graph::outputPath()
{
Vertex* vertex = this->getDestination(); // destination node
// if the node has a shortest path, output it
if(vertex != NULL)
{
// if id and vertex are the same, output zero weight
if(vertex->getId() == this->getSource()->getId())
{
std::cout << vertex->getId() << "->" << vertex->getId() << " ";
}
// create stack using parent vertices
else
{
std::stack path;
while(vertex != this->getSource())
{
path.push(vertex->getId());
vertex = vertex->getParent();
}
if(vertex == this->getSource())
{
path.push(vertex->getId());
}
// pop elements from stack and print
while(path.size())
{
int id = path.top();
path.pop();
if(id == this->getDestination()->getId())
{
std::cout << id << " ";
}
else
{
std::cout << id << "->";
}
}
}
// print out weight to two degrees of precision
double weight = (mWeights[this->getDestination()->getId()])->getWeight();
std::cout << std::fixed << std::setprecision(2) << weight << std::endl;
}
else
{
std::cout << "NO PATH FOUND" << std::endl;
}
}
Vertex.h
/*-----------------------------------------------------------
* Name: Vertex
* Purpose: Represent vertex in a graph
*-----------------------------------------------------------*/
class Vertex
{
public:
// default constructor
Vertex(){mParent = NULL;}
// constructor with defined id
Vertex(int id){mId = id; mParent = NULL;}
~Vertex(){}
// set the vertex id
void setId(int id){mId = id;}
// get the vertex id
int getId() const {return mId;}
// set the total current path weight for a vertex
void setWeight(double weight){mWeight = weight;}
// get the total current path weight for a vertex
double getWeight()const{return mWeight;}
// set a vertex that points to the current vertex
void setParent(Vertex* parent){mParent = parent;}
//get the vertex that points at the current vertex
Vertex* getParent(){return mParent;}
// add an edge to the current vertex
void addEdge(int, double);
// return the map of edges that the current vertex contains
std::map* getEdges(){return &mEdges;}
private:
int mId; //unique id of vertex
double mWeight; //current path weight of vertex
std::map mEdges; //edges from current vertex
Vertex* mParent; //parent vertex
};
/*--------------------------------------------------------
* Name: addEdge
* Purpose: add edge to list of edges to given vertex
*-------------------------------------------------------*/
void Vertex::addEdge(int index, double weight)
{
mEdges.insert(std::make_pair(index,weight));
}
graph.txt
0 3 1
0 1 .51
5 0 3.0
2 5 0.2
5 6 0.8
1 6 1.0
2 4 1.30
4 3 3
3 1 3

More Related Content

Similar to Write CC++ a program that inputs a weighted undirected graph and fi.pdf

in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
michardsonkhaicarr37
 
2Part I1. Answer questions for the following graph, if .docx
2Part I1. Answer questions for the following graph, if .docx2Part I1. Answer questions for the following graph, if .docx
2Part I1. Answer questions for the following graph, if .docx
gilbertkpeters11344
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
afgt2012
 
6Modify the bfs.java program (Listing A) to find the minimu.docx
6Modify the bfs.java program (Listing  A) to find the minimu.docx6Modify the bfs.java program (Listing  A) to find the minimu.docx
6Modify the bfs.java program (Listing A) to find the minimu.docx
evonnehoggarth79783
 
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docxstudent start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
hanneloremccaffery
 
could you implement this function please, im having issues with it..pdf
could you implement this function please, im having issues with it..pdfcould you implement this function please, im having issues with it..pdf
could you implement this function please, im having issues with it..pdf
feroz544
 
This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdf
kostikjaylonshaewe47
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
#include iostream #include fstream #include cstdlib #.pdf
 #include iostream #include fstream #include cstdlib #.pdf #include iostream #include fstream #include cstdlib #.pdf
#include iostream #include fstream #include cstdlib #.pdf
annesmkt
 
Program In C You are required to write an interactive C program that.pdf
Program In C You are required to write an interactive C program that.pdfProgram In C You are required to write an interactive C program that.pdf
Program In C You are required to write an interactive C program that.pdf
amitbagga0808
 

Similar to Write CC++ a program that inputs a weighted undirected graph and fi.pdf (20)

C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
2Part I1. Answer questions for the following graph, if .docx
2Part I1. Answer questions for the following graph, if .docx2Part I1. Answer questions for the following graph, if .docx
2Part I1. Answer questions for the following graph, if .docx
 
String searching
String searchingString searching
String searching
 
Write a program that reads a connected graph from a file and displays.docx
 Write a program that reads a connected graph from a file and displays.docx Write a program that reads a connected graph from a file and displays.docx
Write a program that reads a connected graph from a file and displays.docx
 
#include iostream#include d_node.h #include d_nodel.h.docx
#include iostream#include d_node.h #include d_nodel.h.docx#include iostream#include d_node.h #include d_nodel.h.docx
#include iostream#include d_node.h #include d_nodel.h.docx
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
 
6Modify the bfs.java program (Listing A) to find the minimu.docx
6Modify the bfs.java program (Listing  A) to find the minimu.docx6Modify the bfs.java program (Listing  A) to find the minimu.docx
6Modify the bfs.java program (Listing A) to find the minimu.docx
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docxstudent start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
 
Shapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptShapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop concept
 
C++ adt c++ implementations
C++   adt c++ implementationsC++   adt c++ implementations
C++ adt c++ implementations
 
could you implement this function please, im having issues with it..pdf
could you implement this function please, im having issues with it..pdfcould you implement this function please, im having issues with it..pdf
could you implement this function please, im having issues with it..pdf
 
Stack, queue and hashing
Stack, queue and hashingStack, queue and hashing
Stack, queue and hashing
 
Shapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptShapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop concept
 
This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdf
 
cpp_sample
cpp_samplecpp_sample
cpp_sample
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
#include iostream #include fstream #include cstdlib #.pdf
 #include iostream #include fstream #include cstdlib #.pdf #include iostream #include fstream #include cstdlib #.pdf
#include iostream #include fstream #include cstdlib #.pdf
 
Program In C You are required to write an interactive C program that.pdf
Program In C You are required to write an interactive C program that.pdfProgram In C You are required to write an interactive C program that.pdf
Program In C You are required to write an interactive C program that.pdf
 

More from 4babies2010

Discuss bio films , formation location etc Discuss bio films , .pdf
Discuss bio films , formation location etc Discuss bio films , .pdfDiscuss bio films , formation location etc Discuss bio films , .pdf
Discuss bio films , formation location etc Discuss bio films , .pdf
4babies2010
 
Discuss the importance of documentation in the medical record.So.pdf
Discuss the importance of documentation in the medical record.So.pdfDiscuss the importance of documentation in the medical record.So.pdf
Discuss the importance of documentation in the medical record.So.pdf
4babies2010
 
Define each class of incident.types of incidents classifcationsr.pdf
Define each class of incident.types of incidents classifcationsr.pdfDefine each class of incident.types of incidents classifcationsr.pdf
Define each class of incident.types of incidents classifcationsr.pdf
4babies2010
 
What were the triumphs and limitations of democracy in Periclean Ath.pdf
What were the triumphs and limitations of democracy in Periclean Ath.pdfWhat were the triumphs and limitations of democracy in Periclean Ath.pdf
What were the triumphs and limitations of democracy in Periclean Ath.pdf
4babies2010
 
What are lichens What are foliose lichensSolutionAnswers .pdf
What are lichens  What are foliose lichensSolutionAnswers .pdfWhat are lichens  What are foliose lichensSolutionAnswers .pdf
What are lichens What are foliose lichensSolutionAnswers .pdf
4babies2010
 
The following is the (incomplete) header file for the class Fracti.pdf
The following is the (incomplete) header file for the class Fracti.pdfThe following is the (incomplete) header file for the class Fracti.pdf
The following is the (incomplete) header file for the class Fracti.pdf
4babies2010
 
Summarize the case Surgery Iturralde v. Hilo Medical Center USA , i.pdf
Summarize the case Surgery Iturralde v. Hilo Medical Center USA , i.pdfSummarize the case Surgery Iturralde v. Hilo Medical Center USA , i.pdf
Summarize the case Surgery Iturralde v. Hilo Medical Center USA , i.pdf
4babies2010
 
std deviationSolutionStandard deviation is the measure of disp.pdf
std deviationSolutionStandard deviation is the measure of disp.pdfstd deviationSolutionStandard deviation is the measure of disp.pdf
std deviationSolutionStandard deviation is the measure of disp.pdf
4babies2010
 

More from 4babies2010 (20)

Find the domain of the function. (Enter your answer using interval no.pdf
Find the domain of the function. (Enter your answer using interval no.pdfFind the domain of the function. (Enter your answer using interval no.pdf
Find the domain of the function. (Enter your answer using interval no.pdf
 
factors that are significant in the development of disease includ.pdf
factors that are significant in the development of disease includ.pdffactors that are significant in the development of disease includ.pdf
factors that are significant in the development of disease includ.pdf
 
economic institutions 8. According to Thomas Piketty, what is the si.pdf
economic institutions 8. According to Thomas Piketty, what is the si.pdfeconomic institutions 8. According to Thomas Piketty, what is the si.pdf
economic institutions 8. According to Thomas Piketty, what is the si.pdf
 
Discuss bio films , formation location etc Discuss bio films , .pdf
Discuss bio films , formation location etc Discuss bio films , .pdfDiscuss bio films , formation location etc Discuss bio films , .pdf
Discuss bio films , formation location etc Discuss bio films , .pdf
 
Discuss the importance of documentation in the medical record.So.pdf
Discuss the importance of documentation in the medical record.So.pdfDiscuss the importance of documentation in the medical record.So.pdf
Discuss the importance of documentation in the medical record.So.pdf
 
Determine the molecular geometry of CO32â».Solution .pdf
Determine the molecular geometry of CO32â».Solution           .pdfDetermine the molecular geometry of CO32â».Solution           .pdf
Determine the molecular geometry of CO32â».Solution .pdf
 
Define each class of incident.types of incidents classifcationsr.pdf
Define each class of incident.types of incidents classifcationsr.pdfDefine each class of incident.types of incidents classifcationsr.pdf
Define each class of incident.types of incidents classifcationsr.pdf
 
Complete a force field analysis for an organization with which you a.pdf
Complete a force field analysis for an organization with which you a.pdfComplete a force field analysis for an organization with which you a.pdf
Complete a force field analysis for an organization with which you a.pdf
 
Why was the iodide ion successful for the SN2 reactions What if you.pdf
Why was the iodide ion successful for the SN2 reactions What if you.pdfWhy was the iodide ion successful for the SN2 reactions What if you.pdf
Why was the iodide ion successful for the SN2 reactions What if you.pdf
 
What were the triumphs and limitations of democracy in Periclean Ath.pdf
What were the triumphs and limitations of democracy in Periclean Ath.pdfWhat were the triumphs and limitations of democracy in Periclean Ath.pdf
What were the triumphs and limitations of democracy in Periclean Ath.pdf
 
What process causes plant ion-uptake to acidify soil What soil pH r.pdf
What process causes plant ion-uptake to acidify soil What soil pH r.pdfWhat process causes plant ion-uptake to acidify soil What soil pH r.pdf
What process causes plant ion-uptake to acidify soil What soil pH r.pdf
 
what is the name and stereochemistry of the compoundSolution.pdf
what is the name and stereochemistry of the compoundSolution.pdfwhat is the name and stereochemistry of the compoundSolution.pdf
what is the name and stereochemistry of the compoundSolution.pdf
 
What are some of the architectural decisions that you need to make w.pdf
What are some of the architectural decisions that you need to make w.pdfWhat are some of the architectural decisions that you need to make w.pdf
What are some of the architectural decisions that you need to make w.pdf
 
What are lichens What are foliose lichensSolutionAnswers .pdf
What are lichens  What are foliose lichensSolutionAnswers .pdfWhat are lichens  What are foliose lichensSolutionAnswers .pdf
What are lichens What are foliose lichensSolutionAnswers .pdf
 
These are questions to be answered in a paper about the Chernobyl in.pdf
These are questions to be answered in a paper about the Chernobyl in.pdfThese are questions to be answered in a paper about the Chernobyl in.pdf
These are questions to be answered in a paper about the Chernobyl in.pdf
 
The following is the (incomplete) header file for the class Fracti.pdf
The following is the (incomplete) header file for the class Fracti.pdfThe following is the (incomplete) header file for the class Fracti.pdf
The following is the (incomplete) header file for the class Fracti.pdf
 
The adjusted trial balance for Tybalt Construction as of December 31.pdf
The adjusted trial balance for Tybalt Construction as of December 31.pdfThe adjusted trial balance for Tybalt Construction as of December 31.pdf
The adjusted trial balance for Tybalt Construction as of December 31.pdf
 
Summarize the case Surgery Iturralde v. Hilo Medical Center USA , i.pdf
Summarize the case Surgery Iturralde v. Hilo Medical Center USA , i.pdfSummarize the case Surgery Iturralde v. Hilo Medical Center USA , i.pdf
Summarize the case Surgery Iturralde v. Hilo Medical Center USA , i.pdf
 
Suppose we draw 2 cards out of a deck of 52. Let A = “the first card.pdf
Suppose we draw 2 cards out of a deck of 52. Let A = “the first card.pdfSuppose we draw 2 cards out of a deck of 52. Let A = “the first card.pdf
Suppose we draw 2 cards out of a deck of 52. Let A = “the first card.pdf
 
std deviationSolutionStandard deviation is the measure of disp.pdf
std deviationSolutionStandard deviation is the measure of disp.pdfstd deviationSolutionStandard deviation is the measure of disp.pdf
std deviationSolutionStandard deviation is the measure of disp.pdf
 

Recently uploaded

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 

Write CC++ a program that inputs a weighted undirected graph and fi.pdf

  • 1. Write C/C++ a program that inputs a weighted undirected graph and finds the shortest path between two vertices using Dijkstra’s algorithm, using indices to order the branching. The program should take three command-line arguments: the name of the graph file, followed by a source vertex, followed by a destination vertex. It should output to standard output the vertices in a shortest path in order, including both the source and destination vertices, as well as the total weight of the path. You may assume that any input graphs will have no negative-weight edges. A user should see something very similar to the following when invoking your program. > ./dijkstra graph.txt 2 3 2 5 6 1 0 3 3.51 > Graph.txt: 7 9 //Represents number of vertices and edges, respectively. Solution main.cpp #include "Dij.h" #include /*--------------------------------------------------------- * Name: main * Purpose: driver module for testing Dij.h * Param: filename, source vertex id, destination vertex id *---------------------------------------------------------*/ int main(int argc, char **argv) { string filename; if ( 1 < argc ) filename.assign( argv[1] ); Graph testGraph; // create Graph object //string filename = argv[1]; // get filename testGraph.createGraph(filename); // populate Graph int source; // source index
  • 2. int destination; // destination index // convert strings to integers stringstream s1(argv[2]); s1 >> source; stringstream s2(argv[3]); s2 >> destination; // find the shortest path testGraph.findPath(source,destination); // print the shortest path testGraph.outputPath(); std::cout << std::endl; } Dij.h #include #include #include #include #include #include #include #include #include #include #include "Vertex.h" #define infinity DBL_MAX using namespace std; /*----------------------------------------------------------- * Name: Graph * Purpose: Represent a graph G{V,E} alongside implementation * of Dijkstra's algorithm
  • 3. *-----------------------------------------------------------*/ class Graph { public: Graph(); ~Graph(); void createGraph(std::string); void findPath(int, int); void outputPath(); void relaxVertex(Vertex*); // set the vertex of which the shortest path is being found void setDestination(Vertex* destination){mDestination = destination;} // get the vertex of which the shortest path is being found Vertex* getDestination(){return mDestination;} // set the vertex that is the starting point of the search void setSource(Vertex* source){mSource = source;} // get the vertex that is the starting point of the search Vertex* getSource(){return mSource;} private: std::vector mVertices; //vector of vertices std::map mWeights; //table of shortest path weights Vertex* mDestination; //destination vertex Vertex* mSource; //source vertex }; /*--------------------------------------------------------- * Name: Default Constructor *---------------------------------------------------------*/
  • 4. Graph::Graph() { mDestination = NULL; mSource = NULL; } /*--------------------------------------------------------- * Name: Destructor *---------------------------------------------------------*/ Graph::~Graph() { //Free memory if(!mVertices.empty()) { while(mVertices.size()) { Vertex * vertex = mVertices.back(); delete vertex; mVertices.pop_back(); } } } /*---------------------------------------------------------- * Name: createGraph * Purpose: parse text file and construct graph * Param: string - name of file to parse *----------------------------------------------------------*/ void Graph::createGraph(std::string filename) { std::ifstream myfile; // ifstream object for opening file myfile.open(filename.c_str(), ios::in); // open file // if file does not exist or failed to open, return
  • 5. if(!myfile.is_open()) { cout << "File failed to open" << endl; return; } // get lines from file for parsing for(std::string line; std::getline(myfile, line);) { std::istringstream ss(line); int index, value; //first node and node pointed at double weight; //edge weight betweeen first and second nodes // Get values from stream ss >> index; ss >> value; ss >> weight; // Add vertex to vertices list if not present if(!mWeights.count(index)) { Vertex * vertex = new Vertex(index); vertex->addEdge(value, weight); mVertices.push_back(vertex); mWeights[index] = vertex; //record vertex in weight map vertex->setWeight(infinity); //intialize weight to infinity } // Otherwise the vertice is present - add another edge
  • 6. else { (mWeights[index])->addEdge(value, weight); } // If vertex has no edges, add to graph if(!mWeights.count(value)) { Vertex * vertex = new Vertex(value); mVertices.push_back(vertex); mWeights[value] = vertex; //record vertex in weight map vertex->setWeight(infinity); //initialize weight to infinity } } // close the file myfile.close(); } /*------------------------------------------------------------ * Name: findPath * Purpose: Implements Dijkstra's algorithm with minHeap * Param: ID of source and destination vertices *------------------------------------------------------------*/ void Graph::findPath(int source, int destination) { // lambda functor for comparing vertices auto compare = [](Vertex*lhs,Vertex*rhs) { return lhs->getWeight() > rhs->getWeight(); }; // index to minimum weight vertex int index = 0; // if the source of destination does not exist, there is no path
  • 7. if(mWeights.count(source) && mWeights.count(destination)) { // initialize source vertex to weight of zero (mWeights[source])->setWeight(0); // heapify std::make_heap(mVertices.begin(), mVertices.end(), compare); // set source node this->setSource(mWeights[source]); // search the graph and update shortest paths while(index+1 != mVertices.size()) { Vertex * vertex = mVertices[index]; //vertex of min weight with edges to search // shortest path found if it has correct id and has been updated if(vertex->getId() == destination && vertex->getWeight() != infinity) { this->setDestination(vertex); //set the destination node break; } // shortest path has not been found, relax edges else { this->relaxVertex(vertex); } //Heapify everything apart from extracted value index+=1; std::make_heap(mVertices.begin() + index, mVertices.end(), compare); } } } /*-------------------------------------------------------------- * Name: relaxVertex
  • 8. * Purpose: update total path weight of a vertex in the graph * Param: vertex whose edges are being searched *-------------------------------------------------------------*/ void Graph::relaxVertex(Vertex* vertex) { std::map* edges = vertex->getEdges(); // search edges of current min vertex for(auto iter = edges->begin(); iter != edges->end(); iter++) { // if the edges have not been seen, update weight if((mWeights[iter->first])->getWeight() == infinity) { // weight is updated to current path weight + edge weight (mWeights[iter->first])->setWeight((mWeights[vertex->getId()])->getWeight() + iter->second); (mWeights[iter->first])->setParent(vertex); } // if the vertex has been updated already, compare current path // if new path is now minimal, update path else if((mWeights[iter->first])->getWeight() > iter->second + (mWeights[vertex->getId()])->getWeight()) { (mWeights[iter->first])->setWeight((mWeights[vertex->getId()])->getWeight() + iter->second); (mWeights[iter->first])->setParent(vertex); } } } /*----------------------------------------------------------------- * Name: outputPath * Purpose: output shortest path for destination node *-----------------------------------------------------------------*/ void Graph::outputPath() {
  • 9. Vertex* vertex = this->getDestination(); // destination node // if the node has a shortest path, output it if(vertex != NULL) { // if id and vertex are the same, output zero weight if(vertex->getId() == this->getSource()->getId()) { std::cout << vertex->getId() << "->" << vertex->getId() << " "; } // create stack using parent vertices else { std::stack path; while(vertex != this->getSource()) { path.push(vertex->getId()); vertex = vertex->getParent(); } if(vertex == this->getSource()) { path.push(vertex->getId()); } // pop elements from stack and print while(path.size()) { int id = path.top(); path.pop(); if(id == this->getDestination()->getId()) { std::cout << id << " ";
  • 10. } else { std::cout << id << "->"; } } } // print out weight to two degrees of precision double weight = (mWeights[this->getDestination()->getId()])->getWeight(); std::cout << std::fixed << std::setprecision(2) << weight << std::endl; } else { std::cout << "NO PATH FOUND" << std::endl; } } Vertex.h /*----------------------------------------------------------- * Name: Vertex * Purpose: Represent vertex in a graph *-----------------------------------------------------------*/ class Vertex { public: // default constructor Vertex(){mParent = NULL;} // constructor with defined id Vertex(int id){mId = id; mParent = NULL;} ~Vertex(){} // set the vertex id void setId(int id){mId = id;} // get the vertex id int getId() const {return mId;}
  • 11. // set the total current path weight for a vertex void setWeight(double weight){mWeight = weight;} // get the total current path weight for a vertex double getWeight()const{return mWeight;} // set a vertex that points to the current vertex void setParent(Vertex* parent){mParent = parent;} //get the vertex that points at the current vertex Vertex* getParent(){return mParent;} // add an edge to the current vertex void addEdge(int, double); // return the map of edges that the current vertex contains std::map* getEdges(){return &mEdges;} private: int mId; //unique id of vertex double mWeight; //current path weight of vertex std::map mEdges; //edges from current vertex Vertex* mParent; //parent vertex }; /*-------------------------------------------------------- * Name: addEdge * Purpose: add edge to list of edges to given vertex *-------------------------------------------------------*/ void Vertex::addEdge(int index, double weight) { mEdges.insert(std::make_pair(index,weight)); } graph.txt 0 3 1 0 1 .51 5 0 3.0 2 5 0.2 5 6 0.8 1 6 1.0 2 4 1.30
  • 12. 4 3 3 3 1 3