本文实例讲述了Python数据结构之图的应用。分享给大家供大家参考,具体如下:
一、图的结构
二、代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
# -*- 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程序设计有所帮助。
原文链接:https://blog.csdn.net/chengqiuming/article/details/78600895