zoukankan      html  css  js  c++  java
  • BFS & DFS

     1 graph = {
     2     'A':['B','C'],
     3     'B':['A','C','D'],
     4     'C':['A','B','D','E'],
     5     'D':['B','C','E','F'],
     6     'E':['C','D'],
     7     'F':['D']
     8 }
     9 def BFS(graph,start):
    10     queue = []
    11     queue.append(start)
    12     seen = set()       #使用集合的效率要比使用list的效率高
    13     seen.add(start)
    14     while len(queue)>0:     #queue不为空的时候
    15         vertex = queue.pop(0)
    16         next_nodes = graph[vertex]
    17         for w in next_nodes:
    18             if w not in seen:
    19                 queue.append(w)
    20                 seen.add(w)     #将见过的添加进去
    21         print(vertex)
    22 def DFS(graph,start):
    23     stack = []
    24     stack.append(start)
    25     seen = set()       #使用集合的效率要比使用list的效率高
    26     seen.add(start)
    27     while len(stack)>0:     #stack不为空的时候
    28         vertex = stack.pop()        #由于是栈所以弹出最后一个元素
    29         next_nodes = graph[vertex]
    30         for w in next_nodes:
    31             if w not in seen:
    32                 stack.append(w)
    33                 seen.add(w)     #将见过的添加进去
    34         print(vertex)
    35 print('BFS')
    36 BFS(graph,'E')
    37 print('*'*100)
    38 print('DFS')
    39 DFS(graph,'E')
  • 相关阅读:
    CSS3旋转动画
    CSS3的动画属性
    CSS选择器
    JS事件委托
    js 轮播图效果
    JS事件冒泡和事件捕获
    JS自定义播放器
    js闭包for循环只执行最后一个值得解决方法
    交通红绿灯
    汉明距
  • 原文地址:https://www.cnblogs.com/Halo-zyh-Go/p/12822559.html
Copyright © 2011-2022 走看看