广度优先算法实现

时间:2017-06-14 00:30:06

标签: algorithm breadth-first-search

我正在尝试实施一种“广度优先”算法作为我在书中看到的变体。

我的问题是算法没有将每个节点的元素添加到队列中。

例如,如果我在“搜索()”功能中搜索名为“mariela”的“黑色实验室”,我将得到正确的输出:“西蒙是一个黑色实验室”

但是,我应该能够在“walter”中找到“黑色实验室”,它与“mariela”相关联,“marie”与“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')

1 个答案:

答案 0 :(得分:0)

您的实现中存在许多问题 - 包括Python和算法。

重写为:

# @param graph  graph to search
# @param start  the node to start at
# @param value  the value to search for
def search(graph, start, value):
  explored = []
  queue = [start]
  while len(queue) > 0:
    # next node to explore
    node = queue.pop()
    # only explore if not already explored
    if node not in explored:
      # node found, search complete
      if node == value:
        return True
      # add children of node to queue
      else:
        explored.append(node)
        queue.extend(graph[node]) # extend is faster than concat (+=)
  return False


graph = {}
graph['walter'] = ['luci', 'kaiser', 'andrea', 'mariela']
graph['andrea'] = ['echo', 'dante', 'walter', 'mariela']
graph['mariela'] = ['ginger', 'simon', 'walter', 'andrea']

# children should be a list
graph['kaiser'] = ['german shepherd'] 
graph['luci'] = ['black cat']
graph['echo'] = ['pitbull']
graph['dante'] = ['pitbull']
graph['ginger'] = ['orange cat']
graph['simon'] = ['black lab']

print search(graph, 'mariela', 'walter')

以下是演示https://repl.it/IkRA/0