![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count all possible walks from a source to a destination with exactly k edges in C++
In this tutorial, we will be discussing a program to find the number of walks from a source to a destination with exactly k edges.
For this we will be provided with a graph and the values of source and destination. Our task is to find all the possible paths starting from the source to the destination having exactly k edges.
Example
#include <iostream> using namespace std; #define V 4 //counting walks using recursion int countwalks(int graph[][V], int u, int v, int k){ if (k == 0 && u == v) return 1; if (k == 1 && graph[u][v]) return 1; if (k <= 0) return 0; int count = 0; //moving to the adjacent nodes for (int i = 0; i < V; i++) if (graph[u][i] == 1) count += countwalks(graph, i, v, k-1); return count; } int main(){ int graph[V][V] = { {0, 1, 1, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 0} }; int u = 0, v = 3, k = 2; cout << countwalks(graph, u, v, k); return 0; }
Output
2
Advertisements