国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python數據結構之圖的實現方法

2019-11-25 17:13:04
字體:
來源:轉載
供稿:網友

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

下面簡要的介紹下:

比如有這么一張圖:

    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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桃源县| 交城县| 寿宁县| 淮安市| 阳原县| 于田县| 永寿县| 泰和县| 阳朔县| 开鲁县| 双鸭山市| 定边县| 尼玛县| 梅河口市| 上蔡县| 武陟县| 洮南市| 永州市| 菏泽市| 临汾市| 梁河县| 和顺县| 确山县| 禄丰县| 轮台县| 高阳县| 潜山县| 昭觉县| 随州市| 鄂州市| 贵港市| 洛扎县| 六盘水市| 西贡区| 图木舒克市| 华阴市| 焉耆| 阜新市| 彰化县| 昂仁县| 和顺县|