python數(shù)據結構之圖的實現(xiàn)方法
更新時間:2015年07月08日 14:36:51 作者:yupeng
這篇文章主要介紹了python數(shù)據結構之圖的實現(xiàn)方法,實例分析了Python圖的表示方法與常用尋路算法的實現(xiàn)技巧,需要的朋友可以參考下
本文實例講述了python數(shù)據結構之圖的實現(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程序設計有所幫助。
相關文章
Python實用小技巧之判斷輸入是否為漢字/英文/數(shù)字
這篇文章主要給大家介紹了關于Python實用小技巧之判斷輸入是否為漢字/英文/數(shù)字的相關資料,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2023-06-06
Python使用cx_Oracle模塊將oracle中數(shù)據導出到csv文件的方法
這篇文章主要介紹了Python使用cx_Oracle模塊將oracle中數(shù)據導出到csv文件的方法,涉及Python中cx_Oracle模塊與csv模塊操作Oracle數(shù)據庫及csv文件的相關技巧,需要的朋友可以參考下2015-05-05
Django-xadmin后臺導入json數(shù)據及后臺顯示信息圖標和主題更改方式
這篇文章主要介紹了Django-xadmin后臺導入json數(shù)據及后臺顯示信息圖標和主題更改方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03

