-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.py
More file actions
40 lines (40 loc) · 1.06 KB
/
graph.py
File metadata and controls
40 lines (40 loc) · 1.06 KB
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
30
31
32
33
34
35
36
37
38
39
40
# -*- coding:utf-8 -*-
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')
print('************************')
print(' path A to D')
print('************************')
for i in r:
print(i)
r = searchGraph(Graph, 'A','E')
print('************************')
print(' path A to E')
print('************************')
for i in r:
print(i)
r = searchGraph(Graph, 'C','E')
print('************************')
print(' path C to E')
print('************************')
for i in r:
print(i)