Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Count all possible paths between two vertices in C++
In this tutorial, we will be discussing a program to find the number of paths between two vertices.
For this we will be provided with a directed graph. Our task is to find the number of paths possible between two given vertices.
Example
#includeusing namespace std; //constructing a directed graph class Graph{ int V; list *adj; void countPathsUtil(int, int, bool [],int &); public: //constructor Graph(int V); void addEdge(int u, int v); int countPaths(int s, int d); }; Graph::Graph(int V){ this->V = V; adj = new list [V]; } void Graph::addEdge(int u, int v){ adj[u].push_back(v); } int Graph::countPaths(int s, int d){ //marking all the vertices // as not visited bool *visited = new bool[V]; memset(visited, false, sizeof(visited)); int pathCount = 0; countPathsUtil(s, d, visited, pathCount); return pathCount; } void Graph::countPathsUtil(int u, int d, bool visited[], int &pathCount){ visited[u] = true; //if current vertex is same as destination, // then increment count if (u == d) pathCount++; //if current vertex is not destination else { list ::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) if (!visited[*i]) countPathsUtil(*i, d, visited,pathCount); } visited[u] = false; } int main(){ Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(2, 0); g.addEdge(2, 1); g.addEdge(1, 3); int s = 2, d = 3; cout Output
3
Advertisements
