日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

广度优先搜索(入门)

發布時間:2024/9/20 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 广度优先搜索(入门) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這里給出一個廣度優先算法的簡單實例,得到的是關系最近的人。

首先,廣度優先搜索可回答兩類問題:

  • 第一類問題:從A點出發,有沒有前往B點的路徑?

  • 第二類問題:從A點出發,前往B點的哪條路徑最短?

實例:假設你經營一個芒果農場,需要尋找芒果銷售商,以便將芒果賣給他,為此你可以在朋友中查找!如果朋友中沒有芒果銷售商,那么你可以在朋友的朋友中查找!算法如下。。

朋友關系網絡

# coding=utf-8 from collections import dequedef 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:',searchedreturn False # 整個while循環之后,還沒有找到就返回Falsesearch("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! >>>

可以看到搜索到了要求的目標,并且是關系最近的一個,這里用到的圖是最簡單的,無權值的有向圖。

其中的散列表的排序是按照圖的關系排序的:

總結

以上是生活随笔為你收集整理的广度优先搜索(入门)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。