//enum for the status of a node
enum Status {
NOT_VISITED,
VISITED
};
//forward declaration
class Node;
//An object of this class represents an edge in the graph.
class Edge
{
private:
Node *orgNode;//the originating vertex
Node *dstNode;//the destination vertex
unsigned cost;//cost of the edge
//An object of this class holds a vertex of the graph
class Node
{
private:
string name;
vector<Edge> adjNodeList;//list of outgoing edges for this vertex
enum Status status;//used in dfs to mark the node visited
public:
Node(string id)
{
name = id;
status = NOT_VISITED;
}
//do not del the adj nodes here...they will be deleted by graph destructor
~Node()
{
adjNodeList.clear();
}
enum Status getStatus()
{
return status;
}
void setStatus(enum Status st)
{
status = st;
}
string getName()
{
return name;
}
void addAdjNode(Node *adj, unsigned cost)
{
//create an edge with 'this' as the originating node and adj as the destination node
Edge newEdge(this, adj, cost);
adjNodeList.push_back(newEdge);
}
//displays all adjacent verticies of this vertex
void displayList()
{
string edgeOp = " -> " ;
for(int i=0 ; i < adjNodeList.size() ; i++)
{
Edge edg = adjNodeList[i];
cout << name << " -> " << edg.getDstNode()->getName() << endl ;
}
}
};
//An object of class graph holds a directed graph
class Graph
{
private:
vector<Node*> nodeList;//list of verticies
bool foundCycle;//true if a cycle is found, false otherwise
int desiredCycSize;
void clearVisited()
{
for(int i = 0; i < nodeList.size() && !foundCycle ; i++)
{
nodeList[i]->setStatus(NOT_VISITED);
}
}
unsigned numOfCities, numOfFlights, cycSize;
//read in number of cities(TODO:in current implementation..not reqd), number of edges and the desired tour size
cin >> numOfCities >> numOfFlights >> cycSize;
cin >> fromCity >> toCity >> cost;
//find if a vertex for the city already exists, if so get that
Node *u = findNodeByName(fromCity);
if(u == NULL)
{
u = new Node(fromCity);
addNewNode(u);
}
//find if a vertex for the city already exists, if so get that
Node *v = findNodeByName(toCity);
if(v == NULL)
{
v = new Node(toCity);
addNewNode(v);
}
};
#endif</code>
Hey there I wrote this code some time back for solving a min distance problem or sth like that....
It goes like this..
Make a node class with whatever you want to put in Make edge class as they really help in simplifying the work..
Make a generic class graph which takes inserts and deletes node...
Make any other functions which you want...
As you can see the code is not all that well written but it was done in the midst of an competition in less than a couple of hours...
So kindly bear up with it.......