|
| 1 | +/* |
| 2 | +* C++ program to count all paths from a source to a |
| 3 | +* destination |
| 4 | +*/ |
| 5 | +#include <vector> |
| 6 | +#include <cassert> |
| 7 | +#include <list> |
| 8 | +#include<iostream> |
| 9 | +using namespace std; |
| 10 | + |
| 11 | +/* |
| 12 | +* A directed graph using adjacency list representation; |
| 13 | +* every vertex holds a list of all neighbouring vertices |
| 14 | +* that can be reached from it. |
| 15 | +*/ |
| 16 | +class Graph { |
| 17 | +public: |
| 18 | + // Construct the graph given the number of vertices... |
| 19 | + Graph(int vertices); |
| 20 | + // Specify an edge between two vertices |
| 21 | + void add_edge(int src, int dst); |
| 22 | + // Call the recursive helper function to count all the |
| 23 | + // paths |
| 24 | + int count_paths(int src, int dst, int vertices); |
| 25 | + |
| 26 | +private: |
| 27 | + int m_vertices; |
| 28 | + list<int>* m_neighbours; |
| 29 | + void path_counter(int src, int dst, int& path_count, vector<bool>visited); |
| 30 | +}; |
| 31 | + |
| 32 | +Graph::Graph(int vertices) |
| 33 | +{ |
| 34 | + m_vertices = vertices; // unused!! |
| 35 | + /* An array of linked lists - each element corresponds |
| 36 | + to a vertex and will hold a list of neighbours...*/ |
| 37 | + m_neighbours = new list<int>[vertices]; |
| 38 | +} |
| 39 | + |
| 40 | +void Graph::add_edge(int src, int dst) |
| 41 | +{ |
| 42 | + m_neighbours[src].push_back(dst); |
| 43 | +} |
| 44 | + |
| 45 | +int Graph::count_paths(int src, int dst, int vertices) |
| 46 | +{ |
| 47 | + int path_count = 0; |
| 48 | + vector<bool>visited(vertices,false); |
| 49 | + path_counter(src, dst, path_count, visited); |
| 50 | + return path_count; |
| 51 | +} |
| 52 | + |
| 53 | +/* |
| 54 | +* A recursive function that counts all paths from src to |
| 55 | +* dst. Keep track of the count in the parameter. |
| 56 | +*/ |
| 57 | +void Graph::path_counter(int src, int dst, int& path_count, vector<bool> visited) |
| 58 | +{ |
| 59 | + // If we've reached the destination, then increment |
| 60 | + // count... |
| 61 | + visited[src]=true; |
| 62 | +if (src == dst) { |
| 63 | + path_count++; |
| 64 | + } |
| 65 | + // ...otherwise recurse into all neighbours... |
| 66 | + else { |
| 67 | + for (auto neighbour : m_neighbours[src]) { |
| 68 | + if(!visited[neighbour]) |
| 69 | + path_counter(neighbour, dst, path_count, visited); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +// Tests... |
| 75 | +int main() |
| 76 | +{ |
| 77 | + // Create a graph given in the above diagram - see link |
| 78 | + Graph g(5); |
| 79 | + g.add_edge(0, 1); |
| 80 | + g.add_edge(0, 2); |
| 81 | + g.add_edge(0, 4); |
| 82 | + g.add_edge(1, 3); |
| 83 | + g.add_edge(1, 4); |
| 84 | + g.add_edge(2, 3); |
| 85 | + g.add_edge(2, 1); |
| 86 | + g.add_edge(3, 2); |
| 87 | + // Validate it... |
| 88 | + cout<<g.count_paths(0, 4,5); |
| 89 | + |
| 90 | + return 0; |
| 91 | +} |
0 commit comments