BFS、DFS和dijkstra算法 -python

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

def bfs(graph,start):
     queue,visited = [start],[start]
     while queue:
            vertex=queue.pop()
            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}

猜你喜欢

转载自blog.csdn.net/weixin_42528089/article/details/83449798