|
| 1 | +/** |
| 2 | + * @file |
| 3 | + * @brief Algorithm to count paths between two nodes in a directed graph using DFS |
| 4 | + * @details |
| 5 | + * This algorithm implements Depth First Search (DFS) to count the number of |
| 6 | + * possible paths between two nodes in a directed graph. It is represented using |
| 7 | + * an adjacency matrix. The algorithm recursively traverses the graph to find |
| 8 | + * all paths from the source node `u` to the destination node `v`. |
| 9 | + * |
| 10 | + * @author [Aditya Borate](https://github.com/adi776borate) |
| 11 | + * @see https://en.wikipedia.org/wiki/Path_(graph_theory) |
| 12 | + */ |
| 13 | + |
| 14 | +#include <vector> /// for std::vector |
| 15 | +#include <iostream> /// for IO operations |
| 16 | +#include <cassert> /// for assert |
| 17 | + |
| 18 | +/** |
| 19 | + * @namespace graph |
| 20 | + * @brief Graph algorithms |
| 21 | + */ |
| 22 | +namespace graph { |
| 23 | + |
| 24 | + /** |
| 25 | + * @brief Counts the number of paths from node `u` to node `v` in a directed graph |
| 26 | + * using Depth First Search (DFS) |
| 27 | + * |
| 28 | + * @param A adjacency matrix representing the graph (1: edge exists, 0: no edge) |
| 29 | + * @param u the starting node |
| 30 | + * @param v the destination node |
| 31 | + * @param n the number of nodes in the graph |
| 32 | + * @returns the number of paths from node `u` to node `v` |
| 33 | + */ |
| 34 | + int count_paths(const std::vector<std::vector<int>> &A, int u, int v, int n) { |
| 35 | + if (u == v) { |
| 36 | + return 1; // Base case: Reached the destination node |
| 37 | + } |
| 38 | + |
| 39 | + int path_count = 0; // Count of all paths from `u` to `v` |
| 40 | + |
| 41 | + for (int i = 0; i < n; i++) { |
| 42 | + if (A[u][i] == 1) { // Check if there is an edge from `u` to `i` |
| 43 | + path_count += count_paths(A, i, v, n); // Recursively explore paths from `i` to `v` |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return path_count; |
| 48 | + } |
| 49 | + |
| 50 | +} // namespace graph |
| 51 | + |
| 52 | +/** |
| 53 | + * @brief Self-test implementations |
| 54 | + * @returns void |
| 55 | + */ |
| 56 | +static void test() { |
| 57 | + // Test case 1: Simple directed graph with multiple paths |
| 58 | + std::vector<std::vector<int>> graph1 = { |
| 59 | + {0, 1, 0, 1, 0}, |
| 60 | + {0, 0, 1, 0, 1}, |
| 61 | + {0, 0, 0, 0, 1}, |
| 62 | + {0, 0, 1, 0, 0}, |
| 63 | + {0, 0, 0, 0, 0} |
| 64 | + }; |
| 65 | + int n1 = 5, u1 = 0, v1 = 4; |
| 66 | + assert(graph::count_paths(graph1, u1, v1, n1) == 3); // There are 3 paths from node 0 to 4 |
| 67 | + std::cout << "All tests have successfully passed!\n"; |
| 68 | +} |
| 69 | + |
| 70 | + |
| 71 | +/** |
| 72 | + * @brief Main function |
| 73 | + * @returns 0 on exit |
| 74 | + */ |
| 75 | +int main() { |
| 76 | + test(); // Run self-test implementations |
| 77 | + return 0; |
| 78 | +} |
0 commit comments