用 C++ 计算从一个源到一个目标恰好有 k 个边的所有可能路径的数量
在本教程中,我们将讨论一个程序,用于查找从一个源到一个目标的、恰好有 k 个边的路径数。
为此,我们将提供一个图以及源和目标的值。我们的任务是找到从源到目标的所有可能路径,这些路径恰好有 k 条边。
示例
#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;
}输出
2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP