zoukankan      html  css  js  c++  java
  • 图的广度优先搜索(BFS)与深度优先搜索(DFS) Python实现

    1.广度优先搜索

     1 # 图的广度优先遍历
     2 # 1.利用队列实现
     3 # 2.从源节点开始依次按照宽度进队列,然后弹出
     4 # 3.每弹出一个节点,就把该节点所有没有进过队列的邻接点放入队列
     5 # 4.直到队列变空
     6 from queue import Queue
     7 def bfs(node):
     8     if node is None:
     9         return
    10     queue = Queue()
    11     nodeSet = set()
    12     queue.put(node)
    13     nodeSet.add(node)
    14     while not queue.empty():
    15         cur = queue.get()               # 弹出元素
    16         print(cur.value)                # 打印元素值
    17         for next in cur.nexts:          # 遍历元素的邻接节点
    18             if next not in nodeSet:     # 若邻接节点没有入过队,加入队列并登记
    19                 nodeSet.add(next)
    20                 queue.put(next)

    2.深度优先搜索

     1 # 图的深度优先遍历
     2 # 1.利用栈实现
     3 # 2.从源节点开始把节点按照深度放入栈,然后弹出
     4 # 3.每弹出一个点,把该节点下一个没有进过栈的邻接点放入栈
     5 # 4.直到栈变空
     6 def dfs(node):
     7     if node is None:
     8         return
     9     nodeSet = set()
    10     stack = []
    11     print(node.value)
    12     nodeSet.add(node)
    13     stack.append(node)
    14     while len(stack) > 0:
    15         cur = stack.pop()               # 弹出最近入栈的节点
    16         for next in cur.nexts:         # 遍历该节点的邻接节点
    17             if next not in nodeSet:    # 如果邻接节点不重复
    18                 stack.append(cur)       # 把节点压入
    19                 stack.append(next)      # 把邻接节点压入
    20                 set.add(next)           # 登记节点
    21                 print(next.value)       # 打印节点值
    22                 break                   # 退出,保持深度优先
  • 相关阅读:
    Linux 配置jdk vim和 Linux 基本操作
    Java02_数据类型
    java01_简介_开发环境
    基于Vue + webpack + Vue-cli 实现分环境打包项目
    理解TCP/IP三次握手与四次挥手的正确姿势
    Vue 项目骨架屏注入与实践
    我的第一个Quartz代码
    hdu5882 Balanced Game
    hdu5883 The Best Path(欧拉路)
    Poj 1273 Drainage Ditches(最大流 Edmonds-Karp )
  • 原文地址:https://www.cnblogs.com/icekx/p/9152452.html
Copyright © 2011-2022 走看看