Python實現BFS,DFS


BFS:隊

graph = {
    "A" : ["B","C"],
    "B" : ["A","C","D"],
    "C" : ["A","B","D","E"],
    "D" : ["B","C","E","F"],
    "E" : ["C","D"],
    "F" : ["D"]
}
def BFS(graph, s):
    queue = []
    queue.append(s) # 向list添加元素,用append()
    seen = set() # 此處為set, python里set用的是hash table, 搜索時比數組要快。
    seen.add(s) # 向set添加函數,用add()
    while (len(queue) > 0):
        vertex = queue.pop(0)  #提取隊頭
        nodes = graph[vertex]  #獲得隊頭元素的鄰接元素
        for w in nodes:
            if w not in seen:
                queue.append(w) #將沒有遍歷過的子節點入隊
                seen.add(w) #標記好已遍歷
        print("當前出隊的是:",vertex)

BFS(graph, 'A')

 


 

 DFS:棧

graph = {
    "A" : ["B","C"],
    "B" : ["A","C","D"],
    "C" : ["A","B","D","E"],
    "D" : ["B","C","E","F"],
    "E" : ["C","D"],
    "F" : ["D"]
}
def DFS(graph, s):
    stack=[]
    stack.append(s) # 向list添加元素,用append()
    seen = set() # 此處為set, python里set用的是hash table, 搜索時比數組要快。
    seen.add(s) # 向set添加函數,用add()
    while (len(stack) > 0):
        vertex = stack.pop() # 彈出最后一個元素
        nodes = graph[vertex]
        for w in nodes:
            if w not in seen:
                stack.append(w)
                seen.add(w)
        print("當前出棧的是",vertex)
DFS(graph, 'A')


 

 BFS:求最短路

def BFS2(graph, s):
    queue = []
    queue.append(s)
    seen = set()
    seen.add(s)
    parent = {s:None} #記錄一下父子節點這樣方便求最短路
    while (len(queue) > 0):
        vertex = queue.pop(0)
        nodes = graph[vertex]
        for w in nodes:
            if w not in seen:
                queue.append(w)
                seen.add(w)
                parent[w] = vertex
        print("當前出隊的是:",vertex)
    return parent

parent = BFS2(graph, 'A')
print("父子表:")
for son in parent:
    print(parent[son],son)
print('F->A的最短路:')
start = 'F'
while start:
    print(start,end='->')
    start= parent[start]
print('EDN')

 

 

 


謝謝燈神的講解,豁然開朗啊喂 :https://www.bilibili.com/video/av25763384/?spm_id_from=333.788.b_7265636f5f6c697374.2

 


免責聲明!

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



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