SlideShare a Scribd company logo
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

PDF
Please finish the codes in Graph.h class.#################### Vert.pdf
PPTX
Implementation of graphs, adjaceny matrix
PDF
#include #include Number of vertices in the graph #define V 9 .pdf
PDF
How would you implement a node classs and an edge class to create .pdf
PDF
Complete the implementation of the Weighted Graph that we began in t.pdf
PDF
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
PPTX
15-bellmanFord.pptx...........................................
PPT
Graphs concept in data structures and algorithms.ppt
Please finish the codes in Graph.h class.#################### Vert.pdf
Implementation of graphs, adjaceny matrix
#include #include Number of vertices in the graph #define V 9 .pdf
How would you implement a node classs and an edge class to create .pdf
Complete the implementation of the Weighted Graph that we began in t.pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
15-bellmanFord.pptx...........................................
Graphs concept in data structures and algorithms.ppt

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

DOCX
This code currently works. Run it and get a screen shot of its ou.docx
PPTX
ExploringPrimsAlgorithmforMinimumSpanningTreesinC.pptx
PDF
Im having trouble figuring out how to code these sections for an a.pdf
PPTX
CPP Homework Help
PPT
Directed Acyclic Graph
PPTX
Data Structures and Agorithm: DS 21 Graph Theory.pptx
PPT
Weighted graphs
PPTX
Dijkstra's Shortest Path Algorithm Working
PDF
implement the following funtions. myg1 and myg2 are seperate. x and .pdf
PPTX
Computer Science Assignment Help
DOCX
This code currently works... Run it and get a screen shot of its .docx
PDF
Unit-10 Graphs .pdf
PPTX
Graph Algorithms
PPTX
BELLMAN_FORD _ALGORITHM IN DATA STRUCTURES
PPT
Graphs.ppt of mathemaics we have to clar all doubts
PPT
Graphs.ppt
PPT
9_graphs2.v4.ppt
PPTX
Data structure and algorithm
PPTX
logic.pptx
PPTX
DATA STRUCTURES.pptx
This code currently works. Run it and get a screen shot of its ou.docx
ExploringPrimsAlgorithmforMinimumSpanningTreesinC.pptx
Im having trouble figuring out how to code these sections for an a.pdf
CPP Homework Help
Directed Acyclic Graph
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Weighted graphs
Dijkstra's Shortest Path Algorithm Working
implement the following funtions. myg1 and myg2 are seperate. x and .pdf
Computer Science Assignment Help
This code currently works... Run it and get a screen shot of its .docx
Unit-10 Graphs .pdf
Graph Algorithms
BELLMAN_FORD _ALGORITHM IN DATA STRUCTURES
Graphs.ppt of mathemaics we have to clar all doubts
Graphs.ppt
9_graphs2.v4.ppt
Data structure and algorithm
logic.pptx
DATA STRUCTURES.pptx
Ad

More from 4babies2010 (20)

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

Recently uploaded (20)

PPTX
master seminar digital applications in india
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Lesson notes of climatology university.
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Institutional Correction lecture only . . .
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
master seminar digital applications in india
Microbial disease of the cardiovascular and lymphatic systems
Lesson notes of climatology university.
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
A systematic review of self-coping strategies used by university students to ...
102 student loan defaulters named and shamed – Is someone you know on the list?
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
O7-L3 Supply Chain Operations - ICLT Program
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Institutional Correction lecture only . . .
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Pharmacology of Heart Failure /Pharmacotherapy of CHF
2.FourierTransform-ShortQuestionswithAnswers.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.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