1. 程式人生 > >圖的廣度優先搜尋--python實現

圖的廣度優先搜尋--python實現

最近在看《演算法圖解》,第六章中的廣度優先搜尋中的題目。自己實現一遍,算是做個記錄吧。

關係網路圖如下:


目的:找到朋友與朋友的朋友這些人中,誰是 Seller。 

大體思路: 首先使用散列表實現圖中關係,然後按關係的遠近(關係梯度),按順序將人名字放著一個佇列裡,最後按佇列一個個                     判斷是不是我們要找的人。

結果:找到朋友中的 Seller,或者搜尋隊列變空,你的關係網中沒有 Seller。

程式碼實現:

# -*-coding:utf-8-*-
from collections import deque

#用散列表實現圖
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["alice"] = ["peggy"]
graph["bob"] = ["anuj", "peggy"]
graph["claire"] = ["thom", "jonny"]
graph["peggy"] = []
graph["anuj"] = []
graph["thom"] = []
graph["jonny"] = []

# 搜尋朋友裡面誰是 seller
def search(name):
	#建立搜尋隊列
	search_queue = deque()
	#初始化搜尋隊列
	search_queue += graph[name]
	#記錄已經搜尋過的人
	searched = []
	#只要佇列不空就一直搜尋
	while len(search_queue) > 0:
		#取出佇列中最先加進去的一個人
		person = search_queue.popleft()
		# 只有他沒有被搜尋過才進行搜尋
		if not person in searched:
			# 檢視是不是seller
			if person_is_seller(person):
				print(person + " is a seller")
				return True
			else:
				# 不是seller,所以將他的朋友都加入搜尋隊列
				search_queue += graph[person]
				# 標記這個人已經被搜尋過了
				searched.append(person)
	return False 
# 判定是不是seller,規則是名字以 m 結尾就是 Seller
def person_is_seller(person):
	if person[-1] == "m":
		return True
	else:
		return False

# 測試
search("you")