递归深度优先搜索python,返回加权总数

时间:2015-10-29 08:47:21

标签: python recursion depth-first-search

我正在尝试在python中编写深度优先搜索功能。我无法返回最短路径的总重量。这就是我到目前为止所拥有的......

def dfs(road,start,end,dist_so_far,path=[]):
    path = path + [start]
    if start == end:
        path.append(path)
        del path[-1]
        print(path)
    for node, weight in roads[start]:
        if node not in path:
            dfs(roads, node, end, dist_so_far, path)
    return #return total weight

我此刻迷失了,对于我需要做什么的任何想法?输入看起来像:

road = {'f': [('d', 2.0), ('g', 7.0)], 
        'b': [('a', 5.0), ('d', 6.0)], 
        'c': [('a', 8.0), ('d', 2.0)], 
        'e': [('d', 12.0), ('g', 3.0)], 
        'g': [('e', 3.0), ('f', 7.0)], 
        'a': [('b', 5.0), ('c', 8.0)], 
        'd': [('b', 6.0), ('c', 2.0), ('e', 12.0), ('f', 2.0)]}

print(dfs(road, 'a', 'b', 0.0))

我需要函数返回总的最短距离。我对python仍然比较新,我已经完全错了。

编辑我想我弄清楚了,我有点不对劲..

def dfs(place, dist_so_far, roads, distances):
    if (place not in distances) or (distances[place] > dist_so_far):
        distances[place] = dist_so_far
        for combo in roads[place]:
            to_city, dist = combo
            dfs(to_city, dist_so_far+dist, roads, distances)

distances = { }
start_place = 'a'
dfs(start_place, 0.0, roads, distances )

if destination in distances :
    print("Distance from {} to {} is {}".format(start_place,destination, distances[destination]))

希望这可以帮助其他人在以后的路上。

1 个答案:

答案 0 :(得分:0)

DFS不会在加权图中返回最短路径,而且对于简单的无向图,并不总是给出最佳答案,在这种情况下您需要使用BFS。想象一下下面的图表:

1
| \
2--3

在此图表中有一个循环,如果您使用DFS查找从1到3的最短路径,您将获得长度为2的1-2-3,而我们可以直接从1到3,但是如果您使用BFS,您将获得正确的结果。

回到你的问题,在加权图表中,你可以使用Dijkstra or Bellman–Ford or Floyed,具体取决于你需要什么或你有什么类型的图表。无论如何,如果你想使用DFS从a->b找到一条路径,你可以使用全局变量来存储距离,并在找到第一条路径后完成算法:

res, found = 0, False
def dfs(roads,start,end,dist_so_far,path=[]):
    global res, found
    if found: return

    path = path + [start]
    if start == end:
        path.append(path)
        del path[-1]
        print(path)
        res = dist_so_far
        found = True
        return

    for node, weight in roads[start]:
        if node not in path:
            dfs(roads, node, end, dist_so_far+weight, path)