forked from bamsarts/DS-ALGO
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpossible paths between two vertices.cpp
91 lines (75 loc) · 1.71 KB
/
possible paths between two vertices.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// C++ program to count all paths from a
// source to a destination.
#include <bits/stdc++.h>
using namespace std;
// A directed graph using adjacency list
// representation
class Graph {
// No. of vertices in graph
int V;
list<int>* adj;
// A recursive function
// used by countPaths()
void countPathsUtil(int, int, 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<int>[V];
}
void Graph::addEdge(int u, int v)
{
// Add v to u’s list.
adj[u].push_back(v);
}
// Returns count of paths from 's' to 'd'
int Graph::countPaths(int s, int d)
{
// Call the recursive helper
// function to print all paths
int pathCount = 0;
countPathsUtil(s, d, pathCount);
return pathCount;
}
// A recursive function to print all paths
// from 'u' to 'd'. visited[] keeps track of
// vertices in current path. path[] stores
// actual vertices and path_index is
// current index in path[]
void Graph::countPathsUtil(int u, int d,
int& pathCount)
{
// If current vertex is same as destination,
// then increment count
if (u == d)
pathCount++;
// If current vertex is not destination
else {
// Recur for all the vertices adjacent to
// current vertex
list<int>::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
countPathsUtil(*i, d, pathCount);
}
}
// Driver Code
int main()
{
// Create a graph given in the above diagram
Graph g(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.addEdge(1, 4);
g.addEdge(2, 4);
int s = 0, d = 3;
cout << g.countPaths(s, d);
return 0;
}