Skip to content

Commit acdc0e1

Browse files
committed
complete bfs
1 parent 874b2e8 commit acdc0e1

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

docs/18_图与图的遍历/graph.md

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,62 @@ graph = {
4646
```
4747
如何『由近及远』地访问节点呢?我们先访问起点 A 的邻居,然后邻居访问完再访问邻居的邻居不就行了?
4848
就是这个思想,不过我们需要一个队列辅助,队列之前说过是一种先进先出结构,我们只需要把起点的邻居先入队,
49-
当邻居访问完了再去访问邻居的邻居就可以了,对于已经访问过的节点,我们用一个 set 记录它就好了。
49+
当邻居访问完了再去访问邻居的邻居就可以了,对于已经访问过的节点,我们用一个 set 记录它就好了。代码如下:
50+
51+
```py
52+
# -*- coding: utf-8 -*-
53+
54+
from collections import deque
55+
56+
57+
GRAPH = {
58+
'A': ['B', 'F'],
59+
'B': ['C', 'I', 'G'],
60+
'C': ['B', 'I', 'D'],
61+
'D': ['C', 'I', 'G', 'H', 'E'],
62+
'E': ['D', 'H', 'F'],
63+
'F': ['A', 'G', 'E'],
64+
'G': ['B', 'F', 'H', 'D'],
65+
'H': ['G', 'D', 'E'],
66+
'I': ['B', 'C', 'D'],
67+
}
68+
69+
70+
class Queue(object):
71+
def __init__(self):
72+
self._deque = deque()
73+
74+
def push(self, value):
75+
return self._deque.append(value)
76+
77+
def pop(self):
78+
return self._deque.popleft()
79+
80+
def __len__(self):
81+
return len(self._deque)
5082

5183

84+
def bfs(graph, start):
85+
search_queue = Queue()
86+
search_queue.push(start)
87+
searched = set()
88+
while search_queue: # 队列不为空就继续
89+
cur_node = search_queue.pop()
90+
if cur_node not in searched:
91+
yield cur_node
92+
searched.add(cur_node)
93+
for node in graph[cur_node]:
94+
search_queue.push(node)
95+
96+
97+
print(list(bfs(GRAPH, 'A'))) # 输出 ['A', 'B', 'F', 'C', 'I', 'G', 'E', 'D', 'H']
98+
```
99+
52100
![](./bfs.png)
53101

102+
### DFS
103+
104+
54105
# 思考题
55106

56107
# 延伸阅读

0 commit comments

Comments
 (0)