用 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