python 广度优先查找 (最短路径)

img

如图,从起点cab开始,查找 终点 bat ,广度优先查找的方法是先从最近的节点查找,当最近的节点都不是要找的内容时,再从次一级的节点查找。

# 广度优先查找:先在最近的里面查找,最近的里面查不到,再在次一级的里面查找。
import queue

q = queue.Queue()

# 图结构
graph = {}
graph['cab'] = ['cat','car']
graph['car'] = ['cat','bar']
graph['cat'] = ['bat','mat']
graph['mat'] = ['bat']
graph['bar'] = ['bat']

end = 'bat'
start = 'cab'
q.put(graph[start])

def search(q):
    while q.qsize():
        for node in q.get():
            if node == end:
                return 1
            else:
                q.put(graph[node])
                return search(q)
    return 0
    
result = search(q)
if result == 1:
    print('Find')
else:
    print('Not exists.')
posted @ 2020-06-03 10:58  wztshine  阅读(1128)  评论(0编辑  收藏  举报