Python实现广度优先策略

# -*- 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章