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

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