DFS基本案例退货问题

时间:2018-07-25 01:29:20

标签: python-3.x recursion depth-first-search

在户外距离受到限制的情况下,我正在使用DFS搜索加权图以找到最短路径。我的代码未按预期工作,没有返回局部最优路径并继续搜索,而是继续沿着经过端点的路径前进,而不是返回并探索其他节点。

请原谅我的初学者错误,我是CS的新手。

感谢您的帮助!

def get_best_path(digraph, start, end, path, max_dist_outdoors, best_dist = None,
              best_path = None):
"""
Finds the shortest path between buildings subject to constraints.

Parameters:
    digraph: Digraph instance
        The graph on which to carry out the search
    start: string
    end: string
        Building number at which to end
    path: list composed of [[list of strings], int, int]
        Represents the current path of nodes being traversed. Contains
        a list of node names, total distance traveled, and total
        distance outdoors.
    max_dist_outdoors: int
        Maximum distance spent outdoors on a path
    best_dist: int
        The smallest distance between the original start and end node
        for the initial problem that you are trying to solve
    best_path: list of strings
        The shortest path found so far between the original start
        and end node.
Returns:
    A tuple with the shortest-path from start to end, represented by
    a list of building numbers (in strings), [n_1, n_2, ..., n_k],
    where there exists an edge from n_i to n_(i+1) in digraph,
    for all 1 <= i < k and the distance of that path.

    If there exists no path that satisfies max_total_dist and
    max_dist_outdoors constraints, then return None.
"""
if start not in digraph.get_nodes() or end not in digraph.get_nodes():
    raise ValueError("Start or End Node not in Digraph")
path[0].append(start)
path[1], path[2] = GetDist(digraph, path[0]) #updated distance
if start == end:                
    return path
else:
    for edge in digraph.get_edges_for_node(start): #edge is type edge
        dest = edge.get_destination()
        if dest not in path[0]:
            if path[2] + int(edge.get_outdoor_distance()) <= max_dist_outdoors:
                newPath = get_best_path(digraph, dest, end, path, max_dist_outdoors, best_dist, best_path)
                if newPath != None:
                    if best_dist == None or best_dist > newPath[1]:
                        best_path = newPath
                        best_dist = GetDist(digraph, best_path[0])[0]
return(path)

0 个答案:

没有答案