欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python实现广度优先策略

程序员文章站 2022-05-22 20:57:27
...
# -*- coding: utf-8 -*-

from collections import deque  # 线性表的模块


# 首先定义一个创建图的类,使用邻接矩阵
class Graph(object):
    def __init__(self, *args, **kwargs):
        self.order = []  # visited order
        self.neighbor = {}

    def add_node(self, node):
        key, val = node
        if not isinstance(val, list):
            print('节点输入时应该为一个线性表')  # 避免不正确的输入
        self.neighbor[key] = val

    # 宽度优先算法的实现
    def BFS(self, root):
        # 首先判断根节点是否为空节点
        if root != None:
            # 存将要被检查的队列元素
            search_queue = deque()
            search_queue.append(root)
            # 存被访问过的节点
            visited = []
        else:
            print('root is None')
            return -1

        while search_queue:
            person = search_queue.popleft()
            self.order.append(person)

            if (not person in visited) and (person in self.neighbor.keys()):
                search_queue += self.neighbor[person]
                visited.append(person)

    def clear(self):
        self.order = []

    def node_print(self):
        for index in self.order:
            print(index, end='  ')


if __name__ == '__main__':
    # 创建一个二叉树图
    g = Graph()
    g.add_node(('A', ['B', 'C']))
    g.add_node(('B', ['D', 'E']))
    g.add_node(('C', ['F']))

    # 进行宽度优先搜索
    g.BFS('A')
    print('宽度优先搜索:')
    print('  ', end='  ')
    g.node_print()
    g.clear()

摘自:https://blog.csdn.net/qq_40276310/article/details/80668401(含有深度优先策略)

deque模块可参考:https://blog.csdn.net/hellojoy/article/details/81281367

相关标签: 算法