|
1 | 1 | # coding: utf-8 |
2 | 2 |
|
3 | | - |
4 | | -def bfs(graph, start, end): |
5 | | - path = [] |
6 | | - visited = [start] |
7 | | - while visited: |
8 | | - current = visited.pop(0) |
9 | | - if current not in path: |
10 | | - path.append(current) |
11 | | - if current == end: |
12 | | - print(path) |
| 3 | +# 算法中的path不是最优的路径, |
| 4 | +# 而是搜索过程中的遍历路径 |
| 5 | +def bfs(graph, start, end): # 广度优先图搜索 |
| 6 | + path = [] # 访问路径链 |
| 7 | + visited = [start] # 访问起始城市加入要访问的列表 |
| 8 | + while visited: # 访问城市不为空 |
| 9 | + current = visited.pop(0) # 弹出当前的城市 |
| 10 | + if current not in path: # 如果当前的城市没有在访问路径中 |
| 11 | + path.append(current) # 将当前的城市添加到访问路径中 |
| 12 | + if current == end: # 如果当前的城市是目标城市 |
| 13 | + print(path) # 输出访问路径 |
13 | 14 | return (True, path) |
14 | | - # 两个顶点不相连,则跳过 |
15 | | - if current not in graph: |
16 | | - continue |
17 | | - visited = visited + graph[current] |
| 15 | + if current not in graph: # 如果当前城市不在图的起点城市中, |
| 16 | + continue # 则不能作为访问的起点,跳过去 |
| 17 | + # 将当前城市的可访问城市添加到要访问的目标城市列表中 |
| 18 | + visited = visited + graph[current] # 并作为优先访问(在后面优先 pop)的目标城市 |
18 | 19 | return (False, path) |
19 | 20 |
|
20 | 21 |
|
21 | | -def dfs(graph, start, end): |
22 | | - path = [] |
23 | | - visited = [start] |
24 | | - while visited: |
25 | | - current = visited.pop(0) |
26 | | - if current not in path: |
27 | | - path.append(current) |
28 | | - if current == end: |
29 | | - print(path) |
| 22 | +def dfs(graph, start, end): # 深度优先图搜索 |
| 23 | + path = [] # 访问路径链 |
| 24 | + visited = [start] # 访问起始城市加入要访问的列表 |
| 25 | + while visited: # 访问城市不为空 |
| 26 | + current = visited.pop(0) # 弹出当前的城市 |
| 27 | + if current not in path: # 如果当前的城市没有在访问路径中 |
| 28 | + path.append(current) # 将当前的城市添加到访问路径中 |
| 29 | + if current == end: # 如果当前的城市是目标城市 |
| 30 | + print(path) # 输出访问路径 |
30 | 31 | return (True, path) |
31 | | - # 两个顶点不相连,则跳过 |
32 | | - if current not in graph: |
33 | | - continue |
34 | | - visited = graph[current] + visited |
| 32 | + if current not in graph: # 如果当前城市不在图的起点城市中, |
| 33 | + continue # 则不能作为访问的起点,跳过去 |
| 34 | + # 将当前城市的可访问城市添加到要访问的目标城市列表中 |
| 35 | + visited = graph[current] + visited # 并将当前的访问列表作为优先的目标城市(在后面的先 pop) |
35 | 36 | return (False, path) |
36 | 37 |
|
37 | 38 |
|
|
0 commit comments