【BFS】【DFS】【最短路径】


def BFS(garph,s):
    '''

    :param garph:图
    :param s: 开始的节点
    :return:
    '''
    queue =[]#存放所有的顺序
    queue.append(s)
    seen=set()

    seen.add(s)
    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)

def DFS(garph,s):
    '''

    :param garph:图
    :param s: 开始的节点
    :return:
    '''
    queue =[]#存放所有的顺序
    queue.append(s)
    seen=set()

    seen.add(s)
    while (len(queue)>0):
        vertex =queue.pop()
        nodes = graph[vertex]
        for w in nodes:
            if w not in seen:
                queue.append(w)
                seen.add(w)
        print(vertex)
def findleastroad(graph,s):
    '''

      :param garph:图
      :param s: 开始的节点
      :return:
      '''
    queue = []  # 存放所有的顺序
    queue.append(s)
    seen = set()
    seen.add(s)
    parent={s:None}#s的前一个点是空

    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

if __name__=='__main__':
    graph = {
        # 通过一个点找到所有的相邻点
        "A": ['B', 'C'],
        "B": ['A', 'C', 'D'],
        "C": ['A', 'B', 'D', 'E'],
        "D": ['B', 'C', 'E', 'F'],
        "E": ['C','D'],
        'F': ['D']
    }
    print('BFS结果:')

    BFS(graph,'A')
    print('DFS结果:')
    DFS(graph,'A')
    print('最短路径')
    parent=findleastroad(graph,'E')
    for key in parent:
        print(key,parent[key])#打印出每一个节点的前一个点
    v='B'
    while v!=None:
        print(v)
        v=parent[v]


你可能感兴趣的:(工作)