人工智能实验课——搜索算法学习基础学习笔记(1)【Python】BFS.DFS

在这里插入图片描述
如何把图用代码表示出来,在这里,我们用到的是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算法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥鼠路易

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值