从源点到目标点恰好经过 k 条边的所有路径
给定一个有向图。另外还给定两个顶点 u 和 v,u 是起始顶点,v 是结束顶点。我们的任务是找到从顶点 u 到 v 恰好经过 k 条边的路径数量。算法中也提供了 k 的值。
使用动态规划,我们需要创建一个 3D 表格,其中行指向 u 的值,列指向 v 的值,深度用于跟踪从起点到终点的边数。
输入和输出
Input: The adjacency matrix of the graph: The destination vertex is 3. K = 2 0 1 1 1 0 0 0 1 0 0 0 1 0 0 0 0 Output: There are 2 Possible Walks, from 0 to 3 with 2 edges.
算法
numberOdWalks(u, v, k)
输入:起始顶点 u、结束顶点 v、边数 k。
输出:恰好经过 k 条边的所有可能路径的数量。
Begin define 3D array count of order (n x n x k+1) //n is number of vertices for edge in range 0 to k, do for i in range 0 to n-1, do for j in range 0 to n-1, do count[i, j, edge] := 0 if edge = 0 and i = j, then count[i, j, edge] := 1 if edge = 1 and (i, j) is connected, then count[i, j, edge] := 1 if edge > 1, then for a in range 0 to n, and adjacent with i do count[i, j, edge] := count[i, j, edge] + count[a, j, edge - 1] done done done done return count[u, v, k] End
示例
#include <iostream> #define NODE 7 using namespace std; int graph[NODE][NODE] = { {0, 1, 1, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 0} }; int numberOfWalks(int u, int v, int k) { int count[NODE][NODE][k+1]; for (int edge = 0; edge <= k; edge++) { //for k edges (0..k) for (int i = 0; i < NODE; i++) { for (int j = 0; j < NODE; j++) { count[i][j][edge] = 0; //initially all values are 0 if (edge == 0 && i == j) //when e is 0 and ith and jth node are same, only one path count[i][j][edge] = 1; if (edge == 1 && graph[i][j]) //when e is 0 and direct path from (i to j), one path count[i][j][edge] = 1; if (edge >1) { //for more than one edges for (int a = 0; a < NODE; a++) // adjacent of source i if (graph[i][a]) count[i][j][edge] += count[a][j][edge-1]; } } } } return count[u][v][k]; } int main() { int u = 0, v = 3, k = 2; cout << "There are "<< numberOfWalks(u, v, k)<<" Possible Walks, from "; cout <<u<<" to "<<v<<" with "<<k<<" edges."; }
输出
There are 2 Possible Walks, from 0 to 3 with 2 edges.
广告