Python数据结构之图的应用示例
本文实例讲述了Python数据结构之图的应用。分享给大家供大家参考,具体如下:
一、图的结构
二、代码
# -*- coding:utf-8 -*- #! python3 def searchGraph(graph,start,end): results =[] generatePath(graph,[start],end,results) results.sort(key =lambda x:len(x)) return results def generatePath(graph,path,end,results): state = path[-1] if state == end: results.append(path) else: for arc in graph[state]: if arc not in path: generatePath(graph,path +[arc],end ,results) if __name__ =='__main__': Graph={'A':['B','C','D'], 'B':['E'], 'C':['D','F'], 'D':['B','E','G'], 'E':[], 'F':['D','G'], 'G':['E']} r = searchGraph(Graph,'A','E') print("******************") print(' path A to E') print("******************") for i in r: print(i)
三、运行结果
******************
path A to E
******************
['A', 'B', 'E']
['A', 'D', 'E']
['A', 'C', 'D', 'E']
['A', 'D', 'B', 'E']
['A', 'D', 'G', 'E']
['A', 'C', 'D', 'B', 'E']
['A', 'C', 'D', 'G', 'E']
['A', 'C', 'F', 'D', 'E']
['A', 'C', 'F', 'G', 'E']
['A', 'C', 'F', 'D', 'B', 'E']
['A', 'C', 'F', 'D', 'G', 'E']
运行效果图如下:
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
相关推荐
xiesheng 2020-08-02
koushr 2020-11-12
zhangxiafll 2020-11-13
kikaylee 2020-10-31
范范 2020-10-28
MILemon 2020-10-22
hugebawu 2020-10-12
LauraRan 2020-09-28
shenwenjie 2020-09-24
omyrobin 2020-09-23
guangcheng 2020-09-22
qiangde 2020-09-13
hanyujianke 2020-08-18
晨曦之星 2020-08-14
xiesheng 2020-08-06
KAIrving 2020-08-02
范范 2020-07-30
chenfei0 2020-07-30