寻找双子峰到金门大桥路线的两个步骤:
- 使用图建立问题模型
- 使用广度优先搜索解决问题
图是什么
图由**节点(node)和边(edge)**组成。
广度优先搜索
广度优先搜索是一种用于图的查找算法,用于解决两类问题:
- 从节点A出发,有路径到节点B吗?
- 从节点A出发,到节点B的最短路径是什么?
路径的存在性
在Facebook,看看与芒果销售商是否有联系
然后依次检查他们是否是芒果销售商
如果我的一级好友没有芒果销售商,就需要搜索二级好友
查找最短路径
搜索范围从起点逐渐向外延展:先检查一度,再检查二度。因此需要按照添加顺序检查,使用队列数据结构实现。
队列
队列只支持两种操作:
- 入队
- 出队
与栈不同的是,队列是先进先出,栈是后进后出。
练习
- 找出从起点到终点的最短路径的长度
一步能够到达的地方:
两个点
两步就能到达F
2. 找出从cab到bat的最短路径的长度
同上,两步
图的实现
使用散列表
graph={}
graph["you"]=["bob","claire","alice"]
graph["claire"]=["jonny","thom"]
graph["bob"]=["peggy","anuj"]
graph["alice"]=["peggy"]
graph["anuj"]=[]
graph["peggy"]=[]
graph["thom"]=[]
graph["jonny"]=[]
注:本图中箭头是有方向的,所以称为有向图。
算法实现
- 创建一个队列,用于储存要检查的人
- 从队列中弹出一个人
- 检查这人是否符合目标
是:finish
否:将这个人的所有邻居加入队列 - 回到第二步
- 如果队列为空,则人际关系网中没有目标
第一步:在python中,可使用degue
来创建一个双端队列
from collections import deque
search_queue=deque()#创建一个队列
search_queue+=graph["you"]#加入你的邻居
第二步
def person_is_seller(name):
return(name[-1]=='m')
def find_seller(search_queue):
while search_queue:
person=search_queue.popleft()#取出第一个人
if person_is_seller(person):
print(person+" is a mango seller!")
return True
else:
search_queue+=graph[person]##第三步,否
return False
find_seller(search_queue)
>>>thom is a mango seller!
True
为了防止无限循环,我们还需要一个表,记录已经检查过的人,跳过他们
def person_is_seller(name):
return(name[-1]=='m')
def find_seller(search_queue):
searched=[]
while search_queue:
person=search_queue.popleft()#取出第一个人
if person_is_seller not in searched:
if person_is_seller(person):
print(person+" is a mango seller!")
return True
else:
search_queue+=graph[person]##第三步,否
searched.append(person)
return False
find_seller(search_queue)
>>>thom is a mango seller!
True
运行时间
运行时间为
O
(
V
+
E
)
O(V+E)
O(V+E)
树的实现
tree={}
tree['起床']=['锻炼','刷牙','打包午餐']
tree['锻炼']=['洗澡']
tree['刷牙']=['吃早餐']
tree['打包午餐']=[]
tree['洗澡']=['穿衣服']
tree['吃早餐']=[]
tree['穿衣服']=[]
seque=deque()
seque+=tree['起床']
def todo_list(seque):
done=[]
while seque:
thing=seque.popleft()
if thing not in done:
print(thing)
done.append(thing)
seque+=tree[thing]
return False
print('起床')
todo_list(seque)
>>>起床
锻炼
刷牙
打包午餐
洗澡
吃早餐
穿衣服
False
所有边都向下指,没有向上的图称为树(有层级结构)