SlideShare a Scribd company logo
1 of 10
Download to read offline
How would you implement a node classs and an edge class to create a undirected and a directed
graph using c++
Please provide a default constructor, copy constructor, accessing functions , and destructor for
each of the classes to print out a graph
( node, edge , directed ,undirected )
V={1,3,3,4,5,6}
E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)}
How would you implement a node classs and an edge class to create a undirected and a directed
graph using c++
Please provide a default constructor, copy constructor, accessing functions , and destructor for
each of the classes to print out a graph
( node, edge , directed ,undirected )
V={1,3,3,4,5,6}
E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)}
Please provide a default constructor, copy constructor, accessing functions , and destructor for
each of the classes to print out a graph
( node, edge , directed ,undirected )
V={1,3,3,4,5,6}
E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)}
Solution
#include
#include
#include
#include
#include
using namespace std;
class Graph;
class Edge;
class Vertex;
class Edge {
int weight;
Vertex * vertex1;
Vertex * vertex2;
public:
int getWeight() const {return weight;}
Vertex* getV1() const {return vertex1;}
Vertex* getV2() const {return vertex2;}
void setWeight(int w){weight=w;}
void setV1(Vertex * v){vertex1=v;}
void setV2(Vertex * v){vertex2=v;}
Edge(int w, Vertex* v1, Vertex* v2){weight=w;vertex1=v1;vertex2=v2;}
};
class Vertex {
string label;
vector edgesLeavingMe;
bool visited;
public:
string getLabel() const {return label;}
vector getEdges()const{return edgesLeavingMe;}
Edge * getEdgeTo(string d){
for (vector::iterator it = edgesLeavingMe.begin(); it != edgesLeavingMe.end(); ++it){
if ((*it)->getV2()->getLabel()==d){
return (*it);
}
}
return 0;
}
void setVisited(bool v){visited=v;}
bool getVisited() {return visited;}
void addEdge(Edge * e){edgesLeavingMe.push_back(e);}
void removeEdge(Edge *
e){edgesLeavingMe.erase(remove(edgesLeavingMe.begin(),edgesLeavingMe.end(),e),edgesLea
vingMe.end());}
void removeEdgeTo(string l){
Edge * e = getEdgeTo(l);
removeEdge(e);
}
Vertex(string l){label=l; visited=false;}
};
class Graph {
vector edges;
map vertices;
public:
Vertex * addVertex(string label){
Vertex * v = new Vertex(label);
vertices[label]=v;
return v;
}
Edge * addEdge(int w, string from, string to);
void removeEdge(string from, string to);
Vertex * getVertexWithlabel(string l);
void removeVertex(string l);
};
class UnDirectedGraph {
vector edges;
map vertices;
public:
Vertex * addVertex(string label){
Vertex * v = new Vertex(label);
vertices[label]=v;
return v;
}
map getVertices(){return vertices;}
vector getEdges(){return edges;}
Edge * addEdge(int w, string from, string to){
if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){
Vertex * vfrom = vertices.find(from)->second;
Vertex * vto = vertices.find(to)->second;
Edge * e = new Edge(w,vfrom,vto);
(*vfrom).addEdge(e);
(*vto).addEdge(e);
edges.push_back(e);
return e;
}
else{
//needt o handle case where vertices did not exist.
return 0;
}
}
Edge * getEdge(string from, string to){
if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){
Vertex * v1 = vertices.find(from)->second;
Vertex* v2 = vertices.find(to)->second;
Edge * e = (*v1).getEdgeTo(to);
return e;
}
else {
//need to handle case where vertices did not exist.
return 0;
}
}
void removeEdge(string from, string to){
Edge * e = getEdge(from,to);
if (e != 0){
edges.erase(remove(edges.begin(),edges.end(),e),edges.end());
(*e).getV1()->removeEdge(e);
(*e).getV2()->removeEdge(e);
}
//handle case where edge did not exist?
}
Vertex * getVertexWithLabel(string l){
if (vertices.find(l) != vertices.end())
return vertices.find(l)->second;
else
return 0;
}
void removeVertex(string l){
Vertex * v = getVertexWithLabel(l);
if (v != 0){
vector edges = getVertexWithLabel(l)->getEdges();
for (vector::iterator it = edges.begin(); it != edges.end(); ++it){
string from = (*it)->getV1()->getLabel();
string to = (*it)->getV2()->getLabel();
removeEdge(from,to);
}
vertices.erase(l);
}
else {
//Need to handle case where vertex does not exist.
}
}
vector whereCanIGo(Vertex * v)
{
vector destinations;
vector edges = v->getEdges();
for (vector::const_iterator it = edges.begin(); it != edges.end(); ++it) {
if ((*it)->getV1() != v){
destinations.push_back((*it)->getV1());
}
if ((*it)->getV2() !=v) {
destinations.push_back((*it)->getV2());
}
}
destinations.push_back(v);
return destinations;
}
};
class DirectedGraph {
vector edges;
map vertices;
public:
Vertex * addVertex(string label){
Vertex * v = new Vertex(label);
vertices[label]=v;
return v;
}
map getVertices(){return vertices;}
vector getEdges(){return edges;}
Edge * addEdge(int w, string from, string to){
if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){
Vertex * vfrom = vertices.find(from)->second;
Vertex * vto = vertices.find(to)->second;
Edge * e = new Edge(w,vfrom,vto);
(*vfrom).addEdge(e);
edges.push_back(e);
return e;
}
else{
//handle case where vertcies did not exist.
return 0;
}
}
Edge * getEdge(string from, string to){
if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){
Vertex * v1 = vertices.find(from)->second;
Vertex* v2 = vertices.find(to)->second;
Edge * e = (*v1).getEdgeTo(to);
return e;
}
else {
return 0;
}
}
void removeEdge(string from, string to){
Edge * e = getEdge(from,to);
if (e != 0){
edges.erase(remove(edges.begin(),edges.end(),e),edges.end());
(*e).getV1()->removeEdge(e);
}
}
Vertex * getVertexWithLabel(string l){
if (vertices.find(l) != vertices.end())
return vertices.find(l)->second;
else
return 0;
}
void removeVertex(string l){
Vertex * v = getVertexWithLabel(l);
if (v != 0){
vector edges = getVertexWithLabel(l)->getEdges();
for (vector::iterator it = edges.begin(); it != edges.end(); ++it){
string from = (*it)->getV1()->getLabel();
string to = (*it)->getV2()->getLabel();
removeEdge(from,to);
}
vertices.erase(l);
}
else {
//handle case where vertex did not exist.
}
}
vector whereCanIGo(Vertex * v)
{
vector destinations;
vector edges = v->getEdges();
for (vector::const_iterator it = edges.begin(); it != edges.end(); ++it) {
if ((*it)->getV2() !=v) {
destinations.push_back((*it)->getV2());
}
}
destinations.push_back(v);
return destinations;
}
};
template
void printGraph(T * t){
map vertices = t->getVertices();
for (map::iterator it = vertices.begin(); it != vertices.end(); ++it){
cout << it->first <<": ";
vector edges = it->second->getEdges();
for (vector::iterator jit = edges.begin(); jit != edges.end(); ++jit){
string l1 = (*jit)->getV1()->getLabel();
string l2=(*jit)->getV2()->getLabel();
if (l1 != it->first){cout << l1 << ", ";}
if (l2 != it->first){cout << l2 << ", ";}
}
cout << endl;
}
}
template
bool isPath(T * t, string from, string to)
{
Vertex * vfrom = t->getVertexWithLabel(from);
Vertex * vto = t->getVertexWithLabel(to);
if (vfrom == 0 || vto == 0) {
return false;
}
if (from==to) {
return true;
}
T g = *t;
map vertices = t->getVertices();
vector edges = t->getEdges();
vector verticesToCheck;
verticesToCheck.push_back(vfrom);
vertices.erase(from);
while (verticesToCheck.size() != 0){
vector destinations = t->whereCanIGo(verticesToCheck[0]);
verticesToCheck.erase(verticesToCheck.begin());
for (vector::const_iterator it = destinations.begin(); it != destinations.end(); ++it) {
//
if (vertices.find((*it)->getLabel()) != vertices.end()) {
if ((*it)->getLabel()==to) {
return true;
}
verticesToCheck.push_back((*it));
vertices.erase((*it)->getLabel());
}
}
}
return false;
}
int main(){
UnDirectedGraph g;
g.addVertex("v1");
g.addVertex("v2");
g.addVertex("v3");
g.addEdge(1,"v1","v2");
g.addEdge(1,"v2","v3");
cout << isPath(&g,"v1","v3");
cout << isPath(&g, "v2","v3");
cout << isPath(&g,"v3","v2");
cout << isPath(&g,"v3","v1");
cout << isPath(&g,"v3","v3");
}

More Related Content

Similar to How would you implement a node classs and an edge class to create .pdf

Graphs.ppt of mathemaics we have to clar all doubts
Graphs.ppt of mathemaics  we have to clar all doubtsGraphs.ppt of mathemaics  we have to clar all doubts
Graphs.ppt of mathemaics we have to clar all doubtsnc3186331
 
How to extend map? Or why we need collections redesign? - Scalar 2017
How to extend map? Or why we need collections redesign? - Scalar 2017How to extend map? Or why we need collections redesign? - Scalar 2017
How to extend map? Or why we need collections redesign? - Scalar 2017Szymon Matejczyk
 
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.docxajoy21
 
Extended network and algorithm finding maximal flows
Extended network and algorithm finding maximal flows Extended network and algorithm finding maximal flows
Extended network and algorithm finding maximal flows IJECEIAES
 
Dynamic Semantics Specification and Interpreter Generation
Dynamic Semantics Specification and Interpreter GenerationDynamic Semantics Specification and Interpreter Generation
Dynamic Semantics Specification and Interpreter GenerationEelco Visser
 
Graph in Data Structure
Graph in Data StructureGraph in Data Structure
Graph in Data StructureProf Ansari
 
All pair shortest path by Sania Nisar
All pair shortest path by Sania NisarAll pair shortest path by Sania Nisar
All pair shortest path by Sania NisarSania Nisar
 
ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changeshayato
 
Complete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdfComplete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdfmarketing413921
 
Im looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdfIm looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdfcontact41
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
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 .docxgilbertkpeters11344
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyondFrancis Johny
 
Please implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdfPlease implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdffms12345
 
Write a program that reads a graph from a file and determines whether.docx
 Write a program that reads a graph from a file and determines whether.docx Write a program that reads a graph from a file and determines whether.docx
Write a program that reads a graph from a file and determines whether.docxajoy21
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdfkamdinrossihoungma74
 

Similar to How would you implement a node classs and an edge class to create .pdf (20)

Graphs.ppt
Graphs.pptGraphs.ppt
Graphs.ppt
 
Graphs.ppt of mathemaics we have to clar all doubts
Graphs.ppt of mathemaics  we have to clar all doubtsGraphs.ppt of mathemaics  we have to clar all doubts
Graphs.ppt of mathemaics we have to clar all doubts
 
How to extend map? Or why we need collections redesign? - Scalar 2017
How to extend map? Or why we need collections redesign? - Scalar 2017How to extend map? Or why we need collections redesign? - Scalar 2017
How to extend map? Or why we need collections redesign? - Scalar 2017
 
Array
ArrayArray
Array
 
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
 
Extended network and algorithm finding maximal flows
Extended network and algorithm finding maximal flows Extended network and algorithm finding maximal flows
Extended network and algorithm finding maximal flows
 
Ch4
Ch4Ch4
Ch4
 
Dynamic Semantics Specification and Interpreter Generation
Dynamic Semantics Specification and Interpreter GenerationDynamic Semantics Specification and Interpreter Generation
Dynamic Semantics Specification and Interpreter Generation
 
Graph in Data Structure
Graph in Data StructureGraph in Data Structure
Graph in Data Structure
 
All pair shortest path by Sania Nisar
All pair shortest path by Sania NisarAll pair shortest path by Sania Nisar
All pair shortest path by Sania Nisar
 
ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changes
 
Complete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdfComplete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdf
 
Im looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdfIm looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdf
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
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
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
 
Please implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdfPlease implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdf
 
10 linescan
10 linescan10 linescan
10 linescan
 
Write a program that reads a graph from a file and determines whether.docx
 Write a program that reads a graph from a file and determines whether.docx Write a program that reads a graph from a file and determines whether.docx
Write a program that reads a graph from a file and determines whether.docx
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdf
 

More from info309708

Pluto has been hard to measure from Earth because of its atmosphere. .pdf
Pluto has been hard to measure from Earth because of its atmosphere. .pdfPluto has been hard to measure from Earth because of its atmosphere. .pdf
Pluto has been hard to measure from Earth because of its atmosphere. .pdfinfo309708
 
Loops and ArraysObjectivesArrays are a series of elements consi.pdf
Loops and ArraysObjectivesArrays are a series of elements consi.pdfLoops and ArraysObjectivesArrays are a series of elements consi.pdf
Loops and ArraysObjectivesArrays are a series of elements consi.pdfinfo309708
 
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdfModern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdfinfo309708
 
Let f X Y be a function.True or FalseA sufficient condition for f .pdf
Let f X Y be a function.True or FalseA sufficient condition for f .pdfLet f X Y be a function.True or FalseA sufficient condition for f .pdf
Let f X Y be a function.True or FalseA sufficient condition for f .pdfinfo309708
 
Its your third week on the job at Panache Inc. Last week, you made.pdf
Its your third week on the job at Panache Inc. Last week, you made.pdfIts your third week on the job at Panache Inc. Last week, you made.pdf
Its your third week on the job at Panache Inc. Last week, you made.pdfinfo309708
 
In JAVA Write a program that uses a two-dimensional array to sto.pdf
In JAVA Write a program that uses a two-dimensional array to sto.pdfIn JAVA Write a program that uses a two-dimensional array to sto.pdf
In JAVA Write a program that uses a two-dimensional array to sto.pdfinfo309708
 
How do CCMI model help with the improvements and comparison of the p.pdf
How do CCMI model help with the improvements and comparison of the p.pdfHow do CCMI model help with the improvements and comparison of the p.pdf
How do CCMI model help with the improvements and comparison of the p.pdfinfo309708
 
How do you evaluate your own global mind set levelsSolutionAN.pdf
How do you evaluate your own global mind set levelsSolutionAN.pdfHow do you evaluate your own global mind set levelsSolutionAN.pdf
How do you evaluate your own global mind set levelsSolutionAN.pdfinfo309708
 
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdfHere are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdfinfo309708
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
 
For this homework, you will develop a class called VendingMachine th.pdf
For this homework, you will develop a class called VendingMachine th.pdfFor this homework, you will develop a class called VendingMachine th.pdf
For this homework, you will develop a class called VendingMachine th.pdfinfo309708
 
Discuss what is SSH and the advantages and disadvantages of using it.pdf
Discuss what is SSH and the advantages and disadvantages of using it.pdfDiscuss what is SSH and the advantages and disadvantages of using it.pdf
Discuss what is SSH and the advantages and disadvantages of using it.pdfinfo309708
 
Describe the differences between the three major physical connection .pdf
Describe the differences between the three major physical connection .pdfDescribe the differences between the three major physical connection .pdf
Describe the differences between the three major physical connection .pdfinfo309708
 
Create a student record management system using linked list and queu.pdf
Create a student record management system using linked list and queu.pdfCreate a student record management system using linked list and queu.pdf
Create a student record management system using linked list and queu.pdfinfo309708
 
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdfCoca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdfinfo309708
 
C programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfC programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfinfo309708
 
Biology LabThe poisonous wastes of diptheria germs are called (A).pdf
Biology LabThe poisonous wastes of diptheria germs are called (A).pdfBiology LabThe poisonous wastes of diptheria germs are called (A).pdf
Biology LabThe poisonous wastes of diptheria germs are called (A).pdfinfo309708
 
Aside from the expansion of industrial capitalism, what factors affe.pdf
Aside from the expansion of industrial capitalism, what factors affe.pdfAside from the expansion of industrial capitalism, what factors affe.pdf
Aside from the expansion of industrial capitalism, what factors affe.pdfinfo309708
 
Yates (2009) notes that unions have a purpose broader than serving t.pdf
Yates (2009) notes that unions have a purpose broader than serving t.pdfYates (2009) notes that unions have a purpose broader than serving t.pdf
Yates (2009) notes that unions have a purpose broader than serving t.pdfinfo309708
 
write a C program for blinking light using function make sure it.pdf
write a C program for blinking light using function make sure it.pdfwrite a C program for blinking light using function make sure it.pdf
write a C program for blinking light using function make sure it.pdfinfo309708
 

More from info309708 (20)

Pluto has been hard to measure from Earth because of its atmosphere. .pdf
Pluto has been hard to measure from Earth because of its atmosphere. .pdfPluto has been hard to measure from Earth because of its atmosphere. .pdf
Pluto has been hard to measure from Earth because of its atmosphere. .pdf
 
Loops and ArraysObjectivesArrays are a series of elements consi.pdf
Loops and ArraysObjectivesArrays are a series of elements consi.pdfLoops and ArraysObjectivesArrays are a series of elements consi.pdf
Loops and ArraysObjectivesArrays are a series of elements consi.pdf
 
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdfModern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
 
Let f X Y be a function.True or FalseA sufficient condition for f .pdf
Let f X Y be a function.True or FalseA sufficient condition for f .pdfLet f X Y be a function.True or FalseA sufficient condition for f .pdf
Let f X Y be a function.True or FalseA sufficient condition for f .pdf
 
Its your third week on the job at Panache Inc. Last week, you made.pdf
Its your third week on the job at Panache Inc. Last week, you made.pdfIts your third week on the job at Panache Inc. Last week, you made.pdf
Its your third week on the job at Panache Inc. Last week, you made.pdf
 
In JAVA Write a program that uses a two-dimensional array to sto.pdf
In JAVA Write a program that uses a two-dimensional array to sto.pdfIn JAVA Write a program that uses a two-dimensional array to sto.pdf
In JAVA Write a program that uses a two-dimensional array to sto.pdf
 
How do CCMI model help with the improvements and comparison of the p.pdf
How do CCMI model help with the improvements and comparison of the p.pdfHow do CCMI model help with the improvements and comparison of the p.pdf
How do CCMI model help with the improvements and comparison of the p.pdf
 
How do you evaluate your own global mind set levelsSolutionAN.pdf
How do you evaluate your own global mind set levelsSolutionAN.pdfHow do you evaluate your own global mind set levelsSolutionAN.pdf
How do you evaluate your own global mind set levelsSolutionAN.pdf
 
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdfHere are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
For this homework, you will develop a class called VendingMachine th.pdf
For this homework, you will develop a class called VendingMachine th.pdfFor this homework, you will develop a class called VendingMachine th.pdf
For this homework, you will develop a class called VendingMachine th.pdf
 
Discuss what is SSH and the advantages and disadvantages of using it.pdf
Discuss what is SSH and the advantages and disadvantages of using it.pdfDiscuss what is SSH and the advantages and disadvantages of using it.pdf
Discuss what is SSH and the advantages and disadvantages of using it.pdf
 
Describe the differences between the three major physical connection .pdf
Describe the differences between the three major physical connection .pdfDescribe the differences between the three major physical connection .pdf
Describe the differences between the three major physical connection .pdf
 
Create a student record management system using linked list and queu.pdf
Create a student record management system using linked list and queu.pdfCreate a student record management system using linked list and queu.pdf
Create a student record management system using linked list and queu.pdf
 
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdfCoca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
 
C programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfC programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdf
 
Biology LabThe poisonous wastes of diptheria germs are called (A).pdf
Biology LabThe poisonous wastes of diptheria germs are called (A).pdfBiology LabThe poisonous wastes of diptheria germs are called (A).pdf
Biology LabThe poisonous wastes of diptheria germs are called (A).pdf
 
Aside from the expansion of industrial capitalism, what factors affe.pdf
Aside from the expansion of industrial capitalism, what factors affe.pdfAside from the expansion of industrial capitalism, what factors affe.pdf
Aside from the expansion of industrial capitalism, what factors affe.pdf
 
Yates (2009) notes that unions have a purpose broader than serving t.pdf
Yates (2009) notes that unions have a purpose broader than serving t.pdfYates (2009) notes that unions have a purpose broader than serving t.pdf
Yates (2009) notes that unions have a purpose broader than serving t.pdf
 
write a C program for blinking light using function make sure it.pdf
write a C program for blinking light using function make sure it.pdfwrite a C program for blinking light using function make sure it.pdf
write a C program for blinking light using function make sure it.pdf
 

Recently uploaded

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 artsNbelano25
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
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 17Celine George
 
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...Poonam Aher Patil
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111GangaMaiya1
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
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.pptxJoelynRubio1
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationNeilDeclaro1
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
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 POSCeline George
 

Recently uploaded (20)

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
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.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
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.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
 
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...
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
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
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
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
 

How would you implement a node classs and an edge class to create .pdf

  • 1. How would you implement a node classs and an edge class to create a undirected and a directed graph using c++ Please provide a default constructor, copy constructor, accessing functions , and destructor for each of the classes to print out a graph ( node, edge , directed ,undirected ) V={1,3,3,4,5,6} E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)} How would you implement a node classs and an edge class to create a undirected and a directed graph using c++ Please provide a default constructor, copy constructor, accessing functions , and destructor for each of the classes to print out a graph ( node, edge , directed ,undirected ) V={1,3,3,4,5,6} E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)} Please provide a default constructor, copy constructor, accessing functions , and destructor for each of the classes to print out a graph
  • 2. ( node, edge , directed ,undirected ) V={1,3,3,4,5,6} E={(1,2),(1,4),(2,3),(2,4),(2,5),(3,4),(5,3),(6,3),(6,5)} Solution #include #include #include #include #include using namespace std; class Graph; class Edge; class Vertex; class Edge { int weight; Vertex * vertex1; Vertex * vertex2; public: int getWeight() const {return weight;} Vertex* getV1() const {return vertex1;} Vertex* getV2() const {return vertex2;} void setWeight(int w){weight=w;} void setV1(Vertex * v){vertex1=v;} void setV2(Vertex * v){vertex2=v;} Edge(int w, Vertex* v1, Vertex* v2){weight=w;vertex1=v1;vertex2=v2;} }; class Vertex { string label;
  • 3. vector edgesLeavingMe; bool visited; public: string getLabel() const {return label;} vector getEdges()const{return edgesLeavingMe;} Edge * getEdgeTo(string d){ for (vector::iterator it = edgesLeavingMe.begin(); it != edgesLeavingMe.end(); ++it){ if ((*it)->getV2()->getLabel()==d){ return (*it); } } return 0; } void setVisited(bool v){visited=v;} bool getVisited() {return visited;} void addEdge(Edge * e){edgesLeavingMe.push_back(e);} void removeEdge(Edge * e){edgesLeavingMe.erase(remove(edgesLeavingMe.begin(),edgesLeavingMe.end(),e),edgesLea vingMe.end());} void removeEdgeTo(string l){ Edge * e = getEdgeTo(l); removeEdge(e); } Vertex(string l){label=l; visited=false;} }; class Graph { vector edges; map vertices; public: Vertex * addVertex(string label){ Vertex * v = new Vertex(label); vertices[label]=v; return v; } Edge * addEdge(int w, string from, string to); void removeEdge(string from, string to);
  • 4. Vertex * getVertexWithlabel(string l); void removeVertex(string l); }; class UnDirectedGraph { vector edges; map vertices; public: Vertex * addVertex(string label){ Vertex * v = new Vertex(label); vertices[label]=v; return v; } map getVertices(){return vertices;} vector getEdges(){return edges;} Edge * addEdge(int w, string from, string to){ if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){ Vertex * vfrom = vertices.find(from)->second; Vertex * vto = vertices.find(to)->second; Edge * e = new Edge(w,vfrom,vto); (*vfrom).addEdge(e); (*vto).addEdge(e); edges.push_back(e); return e; } else{ //needt o handle case where vertices did not exist. return 0; } } Edge * getEdge(string from, string to){ if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){ Vertex * v1 = vertices.find(from)->second; Vertex* v2 = vertices.find(to)->second; Edge * e = (*v1).getEdgeTo(to); return e; }
  • 5. else { //need to handle case where vertices did not exist. return 0; } } void removeEdge(string from, string to){ Edge * e = getEdge(from,to); if (e != 0){ edges.erase(remove(edges.begin(),edges.end(),e),edges.end()); (*e).getV1()->removeEdge(e); (*e).getV2()->removeEdge(e); } //handle case where edge did not exist? } Vertex * getVertexWithLabel(string l){ if (vertices.find(l) != vertices.end()) return vertices.find(l)->second; else return 0; } void removeVertex(string l){ Vertex * v = getVertexWithLabel(l); if (v != 0){ vector edges = getVertexWithLabel(l)->getEdges(); for (vector::iterator it = edges.begin(); it != edges.end(); ++it){ string from = (*it)->getV1()->getLabel(); string to = (*it)->getV2()->getLabel(); removeEdge(from,to); } vertices.erase(l); } else { //Need to handle case where vertex does not exist. } } vector whereCanIGo(Vertex * v)
  • 6. { vector destinations; vector edges = v->getEdges(); for (vector::const_iterator it = edges.begin(); it != edges.end(); ++it) { if ((*it)->getV1() != v){ destinations.push_back((*it)->getV1()); } if ((*it)->getV2() !=v) { destinations.push_back((*it)->getV2()); } } destinations.push_back(v); return destinations; } }; class DirectedGraph { vector edges; map vertices; public: Vertex * addVertex(string label){ Vertex * v = new Vertex(label); vertices[label]=v; return v; } map getVertices(){return vertices;} vector getEdges(){return edges;} Edge * addEdge(int w, string from, string to){ if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){ Vertex * vfrom = vertices.find(from)->second; Vertex * vto = vertices.find(to)->second; Edge * e = new Edge(w,vfrom,vto); (*vfrom).addEdge(e); edges.push_back(e); return e; } else{
  • 7. //handle case where vertcies did not exist. return 0; } } Edge * getEdge(string from, string to){ if (vertices.find(from) != vertices.end() && vertices.find(to) != vertices.end()){ Vertex * v1 = vertices.find(from)->second; Vertex* v2 = vertices.find(to)->second; Edge * e = (*v1).getEdgeTo(to); return e; } else { return 0; } } void removeEdge(string from, string to){ Edge * e = getEdge(from,to); if (e != 0){ edges.erase(remove(edges.begin(),edges.end(),e),edges.end()); (*e).getV1()->removeEdge(e); } } Vertex * getVertexWithLabel(string l){ if (vertices.find(l) != vertices.end()) return vertices.find(l)->second; else return 0; } void removeVertex(string l){ Vertex * v = getVertexWithLabel(l); if (v != 0){ vector edges = getVertexWithLabel(l)->getEdges(); for (vector::iterator it = edges.begin(); it != edges.end(); ++it){ string from = (*it)->getV1()->getLabel(); string to = (*it)->getV2()->getLabel(); removeEdge(from,to);
  • 8. } vertices.erase(l); } else { //handle case where vertex did not exist. } } vector whereCanIGo(Vertex * v) { vector destinations; vector edges = v->getEdges(); for (vector::const_iterator it = edges.begin(); it != edges.end(); ++it) { if ((*it)->getV2() !=v) { destinations.push_back((*it)->getV2()); } } destinations.push_back(v); return destinations; } }; template void printGraph(T * t){ map vertices = t->getVertices(); for (map::iterator it = vertices.begin(); it != vertices.end(); ++it){ cout << it->first <<": "; vector edges = it->second->getEdges(); for (vector::iterator jit = edges.begin(); jit != edges.end(); ++jit){ string l1 = (*jit)->getV1()->getLabel(); string l2=(*jit)->getV2()->getLabel(); if (l1 != it->first){cout << l1 << ", ";} if (l2 != it->first){cout << l2 << ", ";} } cout << endl; } } template
  • 9. bool isPath(T * t, string from, string to) { Vertex * vfrom = t->getVertexWithLabel(from); Vertex * vto = t->getVertexWithLabel(to); if (vfrom == 0 || vto == 0) { return false; } if (from==to) { return true; } T g = *t; map vertices = t->getVertices(); vector edges = t->getEdges(); vector verticesToCheck; verticesToCheck.push_back(vfrom); vertices.erase(from); while (verticesToCheck.size() != 0){ vector destinations = t->whereCanIGo(verticesToCheck[0]); verticesToCheck.erase(verticesToCheck.begin()); for (vector::const_iterator it = destinations.begin(); it != destinations.end(); ++it) { // if (vertices.find((*it)->getLabel()) != vertices.end()) { if ((*it)->getLabel()==to) { return true; } verticesToCheck.push_back((*it)); vertices.erase((*it)->getLabel()); } } } return false; } int main(){ UnDirectedGraph g; g.addVertex("v1"); g.addVertex("v2");
  • 10. g.addVertex("v3"); g.addEdge(1,"v1","v2"); g.addEdge(1,"v2","v3"); cout << isPath(&g,"v1","v3"); cout << isPath(&g, "v2","v3"); cout << isPath(&g,"v3","v2"); cout << isPath(&g,"v3","v1"); cout << isPath(&g,"v3","v3"); }