编程语言
首页 > 编程语言> > 最短距离算法Python

最短距离算法Python

作者:互联网

我想创建一个简单的广度优先搜索算法,该算法返回最短路径.

演员信息字典将演员映射到演员出现的电影列表:

actor_info = { "act1" : ["movieC", "movieA"], "act2" : ["movieA", "movieB"], 
     "act3" :["movieA", "movieB"], "act4" : ["movieC", "movieD"], 
     "act5" : ["movieD", "movieB"], "act6" : ["movieE"], 
     "act7" : ["movieG", "movieE"], "act8" : ["movieD", "movieF"], 
     "KevinBacon" : ["movieF"], "act10" : ["movieG"], "act11" : ["movieG"] }

与此相反的是,将电影映射到其中出现的演员列表:

movie_info = {'movieB': ['act2', 'act3', 'act5'], 'movieC': ['act1', 'act4'], 
      'movieA': ['act1', 'act2', 'act3'], 'movieF': ['KevinBacon', 'act8'], 
      'movieG': ['act7', 'act10', 'act11'], 'movieD': ['act8', 'act4', 'act5'], 
      'movieE': ['act6', 'act7']}

所以打个电话

shortest_dictance("act1", "Kevin Bacon", actor_info, movie_info)

我应该得到3,因为act1与act4一起出现在movieC中,而与Kevin8的电影F中出现了Act8一起出现在movieD中.所以最短距离是3.

到目前为止,我有这个:

def shotest_distance(actA, actB, actor_info, movie_info):
   '''Return the number of movies required to connect actA and actB. 
   If theres no connection return -1.'''

    # So we keep 2 lists of actors:
    #   1.The actors that we have already investigated.
    #   2.The actors that need to be investigated because we have found a 
    #      connection beginning at actA. This list must be 
    #      ordered, since we want to investigate actors in the order we 
    #      discover them.
    #      -- Each time we put an actor in this list, we also store
    #         her distance from actA.
    investigated = []
    to_investigate = [actA]
    distance = 0
    while actB not in to_investigate and to_investigate!= []:
        for actor in to_investigate:
            to_investigated.remove(actA)
            investigated.append(act)

            for movie in actor_info[actor]:
                for co_star in movie_info[movie]:
                    if co_star not in (investigated and to_investigate):
                        to_investigate.append(co_star)

 ....
 ....

 return d    

我找不到适合的方法来跟踪每次代码迭代发现的距离.同样,该代码在时间上似乎效率很低.

解决方法:

首先从中创建一个图以连接所有节点,然后运行shortest_path代码(可能会有一个高效的图库来代替下面提到的功能来做到这一点,尽管这很优雅),然后找出所有最短路径中的电影名称.

for i in movie_info:
    actor_info[i] = movie_info[i]

def find_shortest_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not start in graph:
        return None
    shortest = None
    for node in graph[start]:
        if node not in path:
            newpath = find_shortest_path(graph, node, end, path)
            if newpath:
                if not shortest or len(newpath) < len(shortest):
                    shortest = newpath
    return shortest

L = find_shortest_path(actor_info, 'act1', 'act2')
print len([i for i in L if i in movie_info])

find_shortest_path来源:http://www.python.org/doc/essays/graphs/

标签:breadth-first-search,python
来源: https://codeday.me/bug/20191202/2085233.html