Skip to content
This repository was archived by the owner on Sep 20, 2018. It is now read-only.

Commit 2ae9f83

Browse files
committed
对深度优先和广度优先进行了注释说明
1 parent a43078c commit 2ae9f83

1 file changed

Lines changed: 28 additions & 27 deletions

File tree

cp16-Template/graph.py

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,38 @@
11
# coding: utf-8
22

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) # 输出访问路径
1314
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)的目标城市
1819
return (False, path)
1920

2021

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) # 输出访问路径
3031
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)
3536
return (False, path)
3637

3738

0 commit comments

Comments
 (0)