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

python數(shù)據(jù)結構之圖的實現(xiàn)方法

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

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

下面簡要的介紹下:

比如有這么一張圖:

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

可以用字典和列表來構建

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

希望本文所述對大家的Python程序設計有所幫助。

相關文章

最新評論

新民市| 日照市| 静海县| 攀枝花市| 白城市| 中江县| 松潘县| 天门市| 金山区| 屏南县| 沂南县| 铜鼓县| 农安县| 巴林左旗| 敦煌市| 商南县| 新丰县| 宁安市| 桃园县| 云南省| 萍乡市| 武功县| 准格尔旗| 西乡县| 江山市| 子长县| 宿州市| 海兴县| 临沂市| 龙陵县| 财经| 武夷山市| 六枝特区| 通河县| 察雅县| 屏边| 连城县| 宜城市| 陇川县| 靖远县| 临漳县|