最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python數(shù)據(jù)結(jié)構(gòu)之圖的實(shí)現(xiàn)方法

 更新時(shí)間:2015年07月08日 14:36:51   作者:yupeng  
這篇文章主要介紹了python數(shù)據(jù)結(jié)構(gòu)之圖的實(shí)現(xiàn)方法,實(shí)例分析了Python圖的表示方法與常用尋路算法的實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了python數(shù)據(jù)結(jié)構(gòu)之圖的實(shí)現(xiàn)方法。分享給大家供大家參考。具體如下:

下面簡(jiǎn)要的介紹下:

比如有這么一張圖:

    A -> B
    A -> C
    B -> C
    B -> D
    C -> D
    D -> C
    E -> F
    F -> C

可以用字典和列表來構(gòu)建

graph = {'A': ['B', 'C'],
       'B': ['C', 'D'],
       'C': ['D'],
       'D': ['C'],
       'E': ['F'],
       'F': ['C']}

找到一條路徑:

def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
      return path
    if not graph.has_key(start):
      return None
    for node in graph[start]:
      if node not in path:
        newpath = find_path(graph, node, end, path)
        if newpath: return newpath
    return None

找到所有路徑:

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
      return [path]
    if not graph.has_key(start):
      return []
    paths = []
    for node in graph[start]:
      if node not in path:
        newpaths = find_all_paths(graph, node, end, path)
        for newpath in newpaths:
          paths.append(newpath)
    return paths

找到最短路徑:

def find_shortest_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
      return path
    if not graph.has_key(start):
      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

希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論

临洮县| 军事| 志丹县| 赤壁市| 城步| 上虞市| 南丰县| 陆丰市| 岑巩县| 遂宁市| 扶沟县| 平湖市| 平谷区| 牙克石市| 金寨县| 长治县| 昌吉市| 台南市| 秦安县| 和平县| 鄂尔多斯市| 香港| 巴彦淖尔市| 陈巴尔虎旗| 澄城县| 安宁市| 象山县| 万荣县| 安化县| 东乡| 稻城县| 虹口区| 旺苍县| 花莲市| 册亨县| 乌拉特中旗| 镇雄县| 赤峰市| 济宁市| 满城县| 莆田市|