给定边的最短路径

问题描述

我想使用k边找到source(u)的最短路径。这个solution似乎有效,但是它搜索边缘为k到给定节点v的路径。如果在到达k之前v的边缘被覆盖怎么办?我只想从u覆盖k边的所有路径中找到最短的路径。无需达到v

上述链接中的代码

# 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_res = shortestPath(graph,i,k - 1) 
            if rec_res != INF: 
                res = min(res,graph[u][i] + rec_res) 
    return res 

# Driver Code 
if __name__ == '__main__': 
    INF = 999999999999
    
    # Let us create the graph shown 
    # in above diagram 
    graph = [[0,4,2,6,5],[INF,INF,3],0]] 
    u = 0
    v = 4
    k = 3
    print("Weight of the shortest path is",shortestPath(graph,k)) 

解决方法

您可能可以修复该代码(完全不传入或查看v-参见下文)。但是我建议您简单地修改Dijkstra的算法,使其最多只能从起始节点处探索3个边缘。 Dijkstra从头开始查找所有最短路径。只需在路径到达第三个边缘时停止它即可(这需要您在保持距离的同时保持边缘计数)。

修改上面的代码也可以,但是肯定要慢一些,因为除非图形是一棵树,否则您将多次查看每个边。

INF = 999999999999
def nearest_in_k_steps(graph,u,k): 
    print(f"Entering {u},{k} steps remaining")
    V = len(graph)
   
    # Base case
    if k == 0: 
        return 0,u

    # Initialize result 
    best_dist = INF 
    best_target = None

    # Go to all adjacents of u and recurse 
    for i in range(V): 
        if graph[u][i] != INF and u != i: 
            candidate_dist,candidate_target = nearest_in_k_steps(graph,i,k - 1) 
            candidate_dist += graph[u][i]
            if candidate_dist < best_dist:
                print(f"Hmm,path via {i} (d={candidate_dist}) is better than via {best_target} (d={best_dist})")
                best_dist = candidate_dist
                best_target = candidate_target

    print(f"Returning from {u},{k} steps remaining: d={best_dist} to {best_target}")
    return best_dist,best_target

# Driver Code 
if __name__ == '__main__': 
    # Let us create the graph shown 
    # in above diagram 
    graph = [[0,4,2,6,5],[INF,INF,3],0]] 
    start = 0
    steps = 3
    nearest_dist,nearest_target = nearest_in_k_steps(graph,start,steps)
    print(f"Node {nearest_target} is the nearest {steps}-step neighbor of {start}: distance = {nearest_dist}")

请注意,这里有一些打印品只是为了帮助您了解代码的工作原理。