欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

本文實例講述了python數(shù)據(jù)結(jié)構(gòu)之圖的實現(xià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

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

相關(guān)文章

  • Python使用cx_Oracle模塊將oracle中數(shù)據(jù)導(dǎo)出到csv文件的方法

    Python使用cx_Oracle模塊將oracle中數(shù)據(jù)導(dǎo)出到csv文件的方法

    這篇文章主要介紹了Python使用cx_Oracle模塊將oracle中數(shù)據(jù)導(dǎo)出到csv文件的方法,涉及Python中cx_Oracle模塊與csv模塊操作Oracle數(shù)據(jù)庫及csv文件的相關(guān)技巧,需要的朋友可以參考下
    2015-05-05
  • Python函數(shù)的嵌套詳解

    Python函數(shù)的嵌套詳解

    這篇文章主要為大家介紹了Python函數(shù)的嵌套,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-01-01
  • Django-xadmin后臺導(dǎo)入json數(shù)據(jù)及后臺顯示信息圖標和主題更改方式

    Django-xadmin后臺導(dǎo)入json數(shù)據(jù)及后臺顯示信息圖標和主題更改方式

    這篇文章主要介紹了Django-xadmin后臺導(dǎo)入json數(shù)據(jù)及后臺顯示信息圖標和主題更改方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • 詳解Python Socket網(wǎng)絡(luò)編程

    詳解Python Socket網(wǎng)絡(luò)編程

    這篇文章主要為大家介紹了Python Socket網(wǎng)絡(luò)編程,主要介紹使用 Python 進行 TCP Socket網(wǎng)絡(luò)編程
    2016-01-01
  • Flask中提供靜態(tài)文件的實例講解

    Flask中提供靜態(tài)文件的實例講解

    在本篇文章里小編給大家分享的是一篇關(guān)于Flask中提供靜態(tài)文件的實例及相關(guān)知識點詳解,有興趣的朋友們可以跟著學(xué)習(xí)下。
    2021-12-12
  • 最新評論