//route between two vertices of directed graph
#include <iostream>
#include <vector>
using namespace std;
struct Node{
int data;
bool visited;
};
class Graph
{
int v;
vector<Node> *adj;
public:
Graph(int v){
this->v=v;
adj = new vector<Node>[v];
};
void addEdge(int src, int dest){
// the vector array is starting from index 0
src--; dest--;
Node a;
a.data=dest;
a.visited=0;
adj[src].push_back(a);
//For undirected Graph
//adj[dest].push_back(src);
};
bool isRoute(int src,int dest);
};
bool Graph::isRoute(int src,int dest){
while(!adj[src].empty()&&!adj[src].back().visited){
if(adj[src].back().data==dest)
return 1;
else{
adj[src].back().visited=1;
bool j=isRoute(adj[src].back().data,dest);
if(j)
return 1;
}
adj[src].pop_back();
}
return 0;
}
int main(){
//creating graph, creating adjacency list of directed graph
Graph g(10);
g.addEdge(1,2);
g.addEdge(1,8);
g.addEdge(2,3);
g.addEdge(3,4);
g.addEdge(5,4);
g.addEdge(5,6);
g.addEdge(6,7);
g.addEdge(6,3);
g.addEdge(7,8);
g.addEdge(8,5);
g.addEdge(9,10);
g.addEdge(9,8);
g.addEdge(10,1);
// add source and destination here
int src=1;
int dest=9;
src--;dest--;
cout << "\nsource node is "<<src+1<<endl;
cout << "destination node is "<<dest+1<<endl;
if(g.isRoute(src,dest))
cout << "yes there is a route \n";
else
cout << "there is no route\n";
return 0;
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.