0
我試圖實現一個「廣度優先」算法,作爲我在書中看到的某種變體。廣度優先算法的實現
我的問題是算法沒有將每個節點的元素添加到隊列中。
舉例來說,如果我搜索的「黑實驗室」之稱的「瑪麗拉」下的「搜索()」函數,我會得到正確的輸出:「西蒙是個黑實驗室」
然而,我應該能夠在「walter」中找到「黑色實驗室」,它與連接到「simon」的「mariela」連接,「simon」是一個「黑色實驗室」,這是行不通的。有我在執行這個算法做了新手的錯誤,或者設置我的圖錯了嗎?
與往常一樣,任何/所有幫助深表感謝!
from collections import deque
# TEST GRAPH -------------
graph = {}
graph['walter'] = ['luci', 'kaiser', 'andrea', 'mariela']
graph['andrea'] = ['echo', 'dante', 'walter', 'mariela']
graph['mariela'] = ['ginger', 'simon', 'walter', 'andrea']
graph['kaiser'] = 'german shepherd'
graph['luci'] = 'black cat'
graph['echo'] = 'pitbull'
graph['dante'] = 'pitbull'
graph['ginger'] = 'orange cat'
graph['simon'] = 'black lab'
def condition_met(name):
if graph[name] == 'black lab':
return name
def search(name):
search_queue = deque()
search_queue += graph[name] # add all elements of "name" to queue
searchedAlready = [] # holding array for people already searched through
while search_queue: # while queue not empty...
person = search_queue.popleft() # pull 1st person from queue
if person not in searchedAlready: # if person hasn't been searched through yet...
if condition_met(person):
print person + ' is a black labrador'
return True
else:
search_queue += graph[person]
searchedAlready.append(person)
return False
search('walter')
#search('mariela')
謝謝。我會給這個鏡頭。 – JohnWayne360
我已經運行你的代碼---打印搜索(圖形,'沃爾特','德國牧羊犬') - 它沒有返回正確的輸出。相反,我收到了一個錯誤。 – JohnWayne360
原因是沒有節點叫做'pitbull'即使你有叫做'pitbull'的子節點,你的圖中沒有一個叫做'pitbull'的節點A)'graph ['pitbull'] = []'或B)將此行'queue.extend(graph [node])'改爲'queue.extend(graph.get(node,[]))'' – EyuelDK