我正在处理生成k边最短路径的问题.以下代码给出了带有预定义k的最短“距离”.
但是,我需要“路径”
对于下面的代码,路径似乎是:
0-> 2-> 3.
编辑:Ajay的代码解决了此问题.但是,每个节点仅需要访问一次.我没有在原始问题中提到这一点.我包括一个额外的数据集来对其进行测试.
# Python3 program to find shortest path
# with exactly k edges
# Define number of vertices in the graph
# and inifinite value
# A naive recursive function to count
# walks from u to v with k edges
def shortestPath(graph,u,v,k):
V = 4
INF = 999999999999
# Base cases
if k == 0 and u == v:
return 0
if k == 1 and graph[u][v] != INF:
return graph[u][v]
if k <= 0:
return INF
# Initialize result
res = INF
# Go to all adjacents of u and recur
for i in range(V):
if graph[u][i] != INF and u != i and v != i:
rec_re