广度优先搜索(入门)

这里给出一个广度优先算法的简单实例,得到的是关系最近的人。

首先,广度优先搜索可回答两类问题:

  • 第一类问题:从A点出发,有没有前往B点的路径?

  • 第二类问题:从A点出发,前往B点的哪条路径最短?

实例:假设你经营一个芒果农场,需要寻找芒果销售商,以便将芒果卖给他,为此你可以在朋友中查找!如果朋友中没有芒果销售商,那么你可以在朋友的朋友中查找!算法如下。。

朋友关系网络


# coding=utf-8
from collections import deque

def person_is_seller(name):
      return name[-1] == 'm'  # 判断是否是以'm'结尾

graph = {} # 此处的排序是按照图的关系排序的
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggm"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []


def search(name):
    search_queue = deque()   # 创建队列,先进先出
    search_queue += graph[name] # 加入联系人   
    searched = []    # 创建已经被检查过的人,避免重复检查

    while search_queue:  # 只要不为空队列,就一直循环
        person = search_queue.popleft()     
        if not person in searched:  # 只要该对象不在检查过的列表中,就检查
            if person_is_seller(person):
                print person + " is a mango seller!"
                return True  # 找到后立即返回,退出循环
            else:
                search_queue += graph[person] # 添加新的联系人到待检查的队列中
                print 'search_queue:',search_queue 
                searched.append(person)  #添加检查过的人到列表中
                print 'searched:',searched
    return False # 整个while循环之后,还没有找到就返回False

search("you")

运行结果:

>>> 
====== RESTART: C:\Users\LiLong\Desktop\Algorithm\search_algorithms.py ======
search_queue: deque(['bob', 'claire', 'peggy'])
searched: ['alice']
search_queue: deque(['claire', 'peggy', 'anuj', 'peggm'])
searched: ['alice', 'bob']
search_queue: deque(['peggy', 'anuj', 'peggm', 'thom', 'jonny'])
searched: ['alice', 'bob', 'claire']
search_queue: deque(['anuj', 'peggm', 'thom', 'jonny'])
searched: ['alice', 'bob', 'claire', 'peggy']
search_queue: deque(['peggm', 'thom', 'jonny'])
searched: ['alice', 'bob', 'claire', 'peggy', 'anuj']
peggm is a mango seller!
>>> 

可以看到搜索到了要求的目标,并且是关系最近的一个,这里用到的图是最简单的,无权值的有向图。

其中的散列表的排序是按照图的关系排序的:

这里写图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值