• Python实现BFS,DFS


    BFS:队

    graph = {
        "A" : ["B","C"],
        "B" : ["A","C","D"],
        "C" : ["A","B","D","E"],
        "D" : ["B","C","E","F"],
        "E" : ["C","D"],
        "F" : ["D"]
    }
    def BFS(graph, s):
        queue = []
        queue.append(s) # 向list添加元素,用append()
        seen = set() # 此处为set, python里set用的是hash table, 搜索时比数组要快。
        seen.add(s) # 向set添加函数,用add()
        while (len(queue) > 0):
            vertex = queue.pop(0)  #提取队头
            nodes = graph[vertex]  #获得队头元素的邻接元素
            for w in nodes:
                if w not in seen:
                    queue.append(w) #将没有遍历过的子节点入队
                    seen.add(w) #标记好已遍历
            print("当前出队的是:",vertex)
    
    BFS(graph, 'A')


     DFS:栈

    graph = {
        "A" : ["B","C"],
        "B" : ["A","C","D"],
        "C" : ["A","B","D","E"],
        "D" : ["B","C","E","F"],
        "E" : ["C","D"],
        "F" : ["D"]
    }
    def DFS(graph, s):
        stack=[]
        stack.append(s) # 向list添加元素,用append()
        seen = set() # 此处为set, python里set用的是hash table, 搜索时比数组要快。
        seen.add(s) # 向set添加函数,用add()
        while (len(stack) > 0):
            vertex = stack.pop() # 弹出最后一个元素
            nodes = graph[vertex]
            for w in nodes:
                if w not in seen:
                    stack.append(w)
                    seen.add(w)
            print("当前出栈的是",vertex)
    DFS(graph, 'A')


     BFS:求最短路

    def BFS2(graph, s):
        queue = []
        queue.append(s)
        seen = set()
        seen.add(s)
        parent = {s:None} #记录一下父子节点这样方便求最短路
        while (len(queue) > 0):
            vertex = queue.pop(0)
            nodes = graph[vertex]
            for w in nodes:
                if w not in seen:
                    queue.append(w)
                    seen.add(w)
                    parent[w] = vertex
            print("当前出队的是:",vertex)
        return parent
    
    parent = BFS2(graph, 'A')
    print("父子表:")
    for son in parent:
        print(parent[son],son)
    print('F->A的最短路:')
    start = 'F'
    while start:
        print(start,end='->')
        start= parent[start]
    print('EDN')


    谢谢灯神的讲解,豁然开朗啊喂 :https://www.bilibili.com/video/av25763384/?spm_id_from=333.788.b_7265636f5f6c697374.2

     

  • 相关阅读:
    php增加自动刷新当前页面
    liunx环境下安装mysql5.7及以上版本
    mysql的主从级联复制的配置
    windowns常用命令
    liunx之使用(mount)挂载技术
    在burpsuite中为什么不能选中设置好的代理?
    c++中向任意目录下写文件
    Hbase——JavaAPI操作笔记
    每周总结(6)(补)
    每周总结(5)
  • 原文地址:https://www.cnblogs.com/chrysanthemum/p/11733644.html
Copyright © 2020-2023  润新知