图
图是非线性的数据结构,由顶点和边组成。如果图中的顶点是有序的,那么图是有方向的,称之为有向图;否则,图是无向图。在图中,由顶点组成的序列称为路径。
在python中,可以采用字典的方式来创建图,图中的每个元素都是字典中的键,该元素所指向的图中其他元素组成键的值。
与树一样,对于图来说,也可以对其进行遍历。除了遍历外,还可以从图中搜索从一个顶点到另一个顶点的所有路径。
示例:使用字典的方式构建有向图,并搜索图中的路径。
图很容易通过列表和词典来构造。比如说,这有一张简单的图:
A -> B
A -> C
B -> C
B -> D
C -> D
D -> C
E -> F
F -> C
这个图有6个节点(A-G)和8个弧。它可以通过下面的Python数据结构来表示:
graph = {'A': ['B', 'C','D'],
'B': [ 'E'],
'C': ['D','F'],
'D': ['B','E','G'],
'E': [],
'F': ['D','G']
'G': ['E']}
笔记
相同的节点不会在返回的路径中出现两次或两次以上(就是说不会包括环)。图的实现一 个很重要的技术,就是回溯:它会去尝试每一种可能,直到找到结果。
python实现
# 找到一条从start到end的路径
def findPath(graph,start,end,path=[]):
path = path + [start]
if start == end:
return path
for node in graph[start]:
if node not in path:
newpath = findPath(graph,node,end,path)
if newpath:
return newpath
return None
# 找到所有从start到end的路径
def findAllPath(graph,start,end,path=[]):
path = path +[start]
if start == end:
return [path]
paths = [] #存储所有路径
for node in graph[start]:
if node not in path:
newpaths = findAllPath(graph,node,end,path)
for newpath in newpaths:
paths.append(newpath)
return paths
# 查找最短路径
def findShortestPath(graph,start,end,path=[]):
path = path +[start]
if start == end:
return path
shortestPath = []
for node in graph[start]:
if node not in path:
newpath = findShortestPath(graph,node,end,path)
if newpath:
if not shortestPath or len(newpath)<len(shortestPath):
shortestPath = newpath
return shortestPath
'''
主程序
'''
graph = {'A': ['B', 'C','D'],
'B': [ 'E'],
'C': ['D','F'],
'D': ['B','E','G'],
'E': [],
'F': ['D','G'],
'G': ['E']}
onepath = findPath(graph,'A','G')
print('一条路径:',onepath)
allpath = findAllPath(graph,'A','G')
print('\n所有路径:',allpath)
shortpath = findShortestPath(graph,'A','G')
print('\n最短路径:',shortpath)
程序结果: