BFS,DFS,dijkstra的python实现

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):
    '''非递归广度优先算法以及两点之间最短路'''
    if not s or  not graph:
        return None
    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=BFS(graph,'E')
v='B'
while v!=None:
    print(v)
    v=parent[v]
    
    
def DfS(graph,s):
    '''深度优先搜索'''
    if not s or not graph:
        return None
    queue=[]
    queue.append(s)
    seen=set()
    seen.add(s)
    while(len(s))>0:
        vertex=queue.pop()
        nodes=graph[vertex]
        for w in nodes:
            if w not in seen:
                queue.append(w)
                seen.add(w)
        print(vertex)
        
        
'''dijkstra算法'''        
graph1={
       'A':{'B':5,'C':1},
       'B':{'A':5,'C':2,'D':1},
       'C':{'A':1,'B':2,'D':4,'E':8},
       'D':{'B':1,'C':4,'E':3,'F':6},
       'E':{'C':8,'D':3},
       'F':{'D':6}
       }
import heapq
import math

def init_distance(graph,s):
    distance={s:0}
    for vertex in graph:
        if vertex != s:
            distance[vertex]=math.inf
    return distance

def dijkstra(graph,s):
    pqueue=[]
    heapq.heappush(pqueue,(0,s))
    seen=set()
    parent={s:None}
    distance=init_distance(graph,s)
    
    while len(pqueue)>0:
        pair=heapq.heappop(pqueue)
        dist=pair[0]
        vertex=pair[1]
        seen.add(vertex)
        nodes=graph[vertex].keys()
        for w in nodes:
            if w not in seen:
                if dist+graph[vertex][w]<distance[w]:
                    heapq.heappush(pqueue,(dist+graph[vertex][w],w))
                    parent[w]=vertex
                    distance[w]=dist+graph[vertex][w]
        return parent,distance
parent,distance=dijkstra(graph1,'A')
print(parent)
print(distance)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、BFS与DFS简介 在理解动态规划、BFS和DFS一文中,已经集合具体例子,介绍了图的BFS与DFS。但是比较...
    小碧小琳阅读 22,589评论 0 6
  • python中的 DFS 与 BFS 文章来源:https://eddmann.com/posts/depth-f...
    英武阅读 11,589评论 1 55
  • 今天早上老师说你在故事里的主题是什么,你在故事里有哪些限制性的信念,有哪里未被满足的需求,有哪些无觉知的情绪...
    誼君阅读 146评论 0 0
  • 10个7年级韩国男生,坐不住、爱说话、交头接耳、四顾茫然、总有几个想通过扮鬼脸来吸引老师的注意,也总有几个最不想的...
    北高地阅读 202评论 3 3
  • 今天在秋叶大叔的微博上看到一句话,“我有敏锐的直觉和粗糙的内心,这才叫坚强的生活,很多人都用反了,内心太敏感了,而...
    看世界的李香君阅读 667评论 0 5

友情链接更多精彩内容