BFS、DFS和dijkstra算法 -python

bfs算法,宽度优先搜索算法。

def bfs(graph,start):
     queue,visited = [start],[start]
     while queue:
            vertex=queue.pop(0)
            for i in graph[vertex]:
                    if i not in visited:
                          visited.append(i)
                          queue.append(i)
     return visited

G={"A":{"B","D"},
    "B":{"C","E"},
    "C":{"E","F"},
    "D":{"G"},
    "E":{"D","F","G","H"},
    "F":{"H"},
    "G":{"H"},
    "H":{}}
print(bfs(G,'A'  ))

【'A', 'B', 'D', 'E', 'C', 'G', 'H', 'F'】

DFS算法:深度优先搜索算法

def dfs(graph,vertex,queue=[]):
        queue.append(vertex)
        for i in graph[vertex]:
               if i not in queue:
                      queue=dfs(graph,i,queue)
        return queue
       
graph = { 1: [ 2, 3 ], 2: [ 4, 5 ],
                    3: [ 5 ], 4: [ 6 ], 5: [ 6 ],
                    6: [ 7 ], 7: [] }


print(dfs(graph,1,))


运行结果[1, 2, 3, 4, 5, 6, 7]

dijkstra 算法:求访问完所有节点的最短路径

G = {1: {2: 5, 4: 2, 5: 7},
     2: {3: 4},
     3: {},
     4: {2: 1, 3: 10},
     5: {3: 3}}

def dijkstra(graph,source):
     visited =set()
     distance = dict((k ,float("inf")) for k in G.keys())
     distance[source]=0
     while len(G)!=len(visited):
          visited.add(source)
          for next_node in  graph[source]:  #已经被访问的点
                 if distance[next_node]>distance[source]+graph[source][next_node]:
                          distance[next_node]=distance[source]+graph[source][next_node]
          INF=float("inf")
          for node in distance.keys():  #已经被访问的点,但是没有被确定为最优化的点
                 if node not in visited and distance[node]< INF:
                         INF,source= distance[node],node
     return distance
distance = dijkstra(G, 1)
print(distance)

 

运行结果:

{1: 0, 2: 3, 3: 7, 4: 2, 5: 7}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值