如何把图用代码表示出来,在这里,我们用到的是python里面的字典。
首先,我们在终端测试。
(base) warmtree@warmtree-HP-Pavilion-Laptop-15-cc5xx:~$ python3
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> graph = {
... "A":["B","C"],
... "B":["A","C","D"],
... "C":["A","B","D","E"],
... "D":["B","C","E","F"],
... "E":["C","D"],
... "F":["D"]
... }
>>> graph.keys()
dict_keys(['A', 'B', 'C', 'D', 'E', 'F'])
>>> #all the name of the nodes
... graph["E"]
['C', 'D']
>>> graph['E']
['C', 'D']
>>> #base use of dictionary in py
... queue=[]
>>> queue.append("A")
>>> queue.append("B")
>>> queue.append("C")
>>> queue
['A', 'B', 'C']
>>> queue.pop(0)
'A'
>>> queue
['B', 'C']
退出模式用exit()
那么,我们开始用BFS来搜索我们的图
graph = {
"A":["B","C"],
"B":["A","C","D"],
"C":["A","B","D","E"],
"D":["B","C","E","F"],
"E":["C","D"],
"F":["D"]
}
def BFS(gragh,s):
#we need a queue在这里,我们仅仅要一个空的数组就可以,
#python 里面我们可以动态添加内容。
queue = []
queue.append(s)
seen = set()#代表一个集合,查找比较块
seen.add(s)#向一个集合添加元素,ADD
while(len(queue)>0):
vertex = queue.pop(0)
nodes = graph[vertex]
for w in nodes:
if w not in seen:
queue.append(w)
seen.add(w)
print(vertex)
BFS(graph,'A')
然后,我们来试验一下DFS,DFS与BFS的区别在于使用的数据类型不同.
使用的是stack类型。首先我们先来做一个简单的测试。
(base) warmtree@warmtree-HP-Pavilion-Laptop-15-cc5xx:~/code/labs$ python3
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> stack = []
>>> stack.append("A")
>>> stack.append("B")
>>> stack.append("C")
>>> stack
['A', 'B', 'C']
>>> stack.pop()
'C'
>>> exit()
(base) warmtree@warmtree-HP-Pavilion-Laptop-15-cc5xx:~/code/labs$ python3 dfs.py
E
D
F
B
A
C
我们自定义的DFS函数如下
def DFS(gragh,s):
stack = []
stack.append(s)
seen = set()#代表一个集合,查找比较块
seen.add(s)#向一个集合添加元素,ADD
while(len(stack)>0):
vertex = stack.pop()#弹出的是最后一个元素
nodes = graph[vertex]
for w in nodes:
if w not in seen:
stack.append(w)
seen.add(w)
print(vertex)
DFS(graph,'E')
参考学习视频: 黄浩杰[Python] BFS和DFS算法