简单图最短路径

graph = {'保安':['巡检', '巡逻', '监控'], '监控':['监视','密切','白领'], '巡逻':['白领', '蓝领', '科学家'], '白领':['销售', '大堂经理', '采购']}
def bfs(graph, root):
    queue = [root]
    seen = {root}
    parent = {root:None}
    while queue:
        node = queue.pop(0)
        print(node)
        neighbors = graph.get(node)
        if neighbors:
            for each in neighbors:
                queue.append(each)
                seen.add(each)
                parent[each] = node
    return parent
parent = test(graph, '监控')
print(parent)
# 从采购出发到监控的最短路径
node = '采购'
while node:
    print(node)
    node = parent[node]

 

posted @ 2023-03-16 16:34  今夜无风  阅读(27)  评论(0编辑  收藏  举报