广度优先搜索指出是否有s到t的路径
如果有,广度优先搜索将找出最短路径
队列是先进先出
栈是后进先出
要按照加入顺序检查搜索列表中的元素,否则找到的就不是最短路径,因此搜索列表必须是队列
对于检查过的元素,务必不要再去检查,否则可能导致无限循环
'''
广度优先搜索指出是否有s到t的路径
如果有,广度优先搜索将找出最短路径
队列是先进先出
栈是后进先出
要按照加入顺序检查搜索列表中的元素,否则找到的就不是最短路径,因此搜索列表必须是队列
对于检查过的元素,务必不要再去检查,否则可能导致无限循环
'''
from collections import deque
graph = {}
graph['s'] = ['b', 'c']
graph['b'] = ['d']
graph['c'] = ['e']
graph['d'] = ['t']
graph['e'] = ['d']
def node_is_final(node):
if(node == 't'):
return True
def search(name):
search_queue = deque() # 创建一个队列
search_queue += graph[name] # 将起点的值传入待搜索队列中
searched = []
while(search_queue):
node = search_queue.popleft()
if not node in searched:
if node_is_final(node):
print(node + ' is the final target')
return True, searched
else:
search_queue += graph[node]
searched.append(node)
return False, searched
if __name__ == '__main__':
result, searched = search('s')
print(searched)