Python数据结构——图(graph)

版权声明:转载请注明出处 https://blog.csdn.net/Rex_WUST/article/details/83272941

图由顶点和边组成。如果图中顶点是有序的,则称之为有向图。

由顶点组成的序列,称为路径。

除了可以对图进行遍历外,还可以搜索图中任意两个顶点之间的最短路径。

在python中,可利用字典 {键:值} 来创建图。

图中的每个顶点,都是字典中的键,该键对应的值为“该顶点所指向的图中其他的顶点”。

# -*- coding:utf-8 -*-
# file: pygraph.py
#
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','D')						# 搜索A到D的所有路径
	print('************************')
	print('     path A to D')
	print('************************')
	for i in r:
		print(i)
	r = searchGraph(Graph, 'A','E')						# 搜索A到E的所有路径
	print('************************')
	print('     path A to E')
	print('************************')
	for i in r:
		print(i)
	r = searchGraph(Graph, 'C','E')						# 搜索C到E的所有路径
	print('************************')
	print('     path C to E')
	print('************************')
	for i in r:
		print(i)

运行结果如下:

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
== RESTART: G:\pygraph.py ==
************************
     path A to D
************************
['A', 'D']
['A', 'C', 'D']
['A', 'C', 'F', 'D']
************************
     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']
************************
     path C to E
************************
['C', 'D', 'E']
['C', 'D', 'B', 'E']
['C', 'D', 'G', 'E']
['C', 'F', 'D', 'E']
['C', 'F', 'G', 'E']
['C', 'F', 'D', 'B', 'E']
['C', 'F', 'D', 'G', 'E']

猜你喜欢

转载自blog.csdn.net/Rex_WUST/article/details/83272941