广度优先搜索(BFS), 深度优先搜索(DFS) 解决图两节点最短路径问题

  • 题目用到的图
    广度优先搜索(BFS), 深度优先搜索(DFS) 解决图两节点最短路径问题_第1张图片
  • 具体代码
# -*- coding:utf-8 -*-

""" 
Author: leadingme
Mail:[email protected]
MyWebsite:leadingme.top
"""
# 用队列实现广度优先搜索
# 用栈实现深度优先搜索
from queue import Queue, LifoQueue

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(maxsize=0)
    queue.put(s)
    seen = set()
    seen.add(s)
    parent = {s: None} # 用于存储每个节点的父节点,求最短距离可用
    while queue.qsize() > 0: # 队列判空
        vertex = queue.get()
        nodes = graph[vertex]  # 元素的所有连接点
        for w in nodes:
            if w not in seen:
                queue.put(w)
                seen.add(w)
                parent[w] = vertex
        # print(vertex)
    return parent

def DFS(graph, s):
    stack = LifoQueue(maxsize=0)
    stack.put(s)
    seen = set()
    seen.add(s)
    while stack.qsize() > 0: # 栈判空
        vertex = stack.get()
        nodes = graph[vertex]
        for w in nodes:
            if w not in seen:
                stack.put(w)
                seen.add(w)
        print(vertex)


if __name__ == '__main__':
    # DFS(graph, "A")
    parent = BFS(graph, "A")
    # print(parent)  {'A': None, 'B': 'A', 'C': 'A', 'D': 'B', 'E': 'C', 'F': 'D'}
    v = "D" # 寻找D到A的最短路线
    while v is not None:
        print(v)  # D -> B -> A
        v = parent[v]



你可能感兴趣的:(数据结构与算法)