python數(shù)據(jù)結(jié)構(gòu)之圖的實現(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調(diào)用實現(xiàn)最小二乘法的方法詳解
所謂線性最小二乘法,可以理解為是解方程的延續(xù),區(qū)別在于,當未知量遠小于方程數(shù)的時候,將得到一個無解的問題。本文主要和大家分享Python調(diào)用實現(xiàn)最小二乘法的方法,需要的可以參考一下2023-04-04Python實用小技巧之判斷輸入是否為漢字/英文/數(shù)字
這篇文章主要給大家介紹了關(guān)于Python實用小技巧之判斷輸入是否為漢字/英文/數(shù)字的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2023-06-06

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

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

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