圖的遍歷(Python實現)


圖的遍歷(Python實現)

記錄兩種圖的遍歷算法——廣度優先(BFS)與深度優先(DFS)。

圖(graph)在物理存儲上采用鄰接表,而鄰接表是用python中的字典來實現的。

兩種遍歷方式的代碼如下所示:

# 圖的寬度遍歷和深度遍歷

# 1. BFS
def bfsTravel(graph, source):
    # 傳入的參數為鄰接表存儲的圖和一個開始遍歷的源節點
    frontiers = [source]     # 表示前驅節點
    travel = [source]       # 表示遍歷過的節點
    # 當前驅節點為空時停止遍歷
    while frontiers:        
        nexts = []          # 當前層的節點(相比frontier是下一層)
        for frontier in frontiers:
            for current in graph[frontier]: # 遍歷當前層的節點
                if current not in travel:   # 判斷是否訪問過
                    travel.append(current)  # 沒有訪問過則入隊
                    nexts.append(current)   # 當前結點作為前驅節點
        frontiers = nexts   # 更改前驅節點列表
    return travel


def dfsTravel(graph, source):
    # 傳入的參數為鄰接表存儲的圖和一個開始遍歷的源節點
    travel = []     # 存放訪問過的節點的列表
    stack = [source]      # 構造一個堆棧
    while stack:            # 堆棧空時結束    
        current = stack.pop()       # 堆頂出隊
        if current not in travel:   # 判斷當前結點是否被訪問過
            travel.append(current)  # 如果沒有訪問過,則將其加入訪問列表
        for next_adj in graph[current]: # 遍歷當前結點的下一級
            if next_adj not in travel:  # 沒有訪問過的全部入棧
                stack.append(next_adj)
    return travel


if __name__ == "__main__":
    graph = {}
    graph['a'] = ['b']
    graph['b'] = ['c','d']
    graph['c'] = ['e']
    graph['d'] = []
    graph['e'] = ['a']

    # test of BFS
    print(bfsTravel(graph, 'b'))

    print(dfsTravel(graph, 'b'))

運行結果如下:

['b', 'c', 'd', 'e', 'a']
['b', 'd', 'c', 'e', 'a']

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM