BFS
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): #s是起始点
queue=[] #数组可以动态的添加或者删除 append、pop
queue.append(s)
seen=[] #来保存放过的节点
seen.append(s)
parent={s:None}#字典
while(len(queue)>0):
vertex=queue.pop(0)
nodes=graph[vertex]
for node in nodes:
if node not in seen:
queue.append(node)
seen.append(node)
parent[node]=vertex
print(vertex) #把当前拿出去的节点打印出来
return parent
parent=BFS(graph,"A")
print(parent)
v="E"
while v!=None: #输出最短路径
print(v)
v=parent[v]
DFS
def DFS(graph,s): #s是起始点
stack=[] #数组可以动态的添加或者删除 append、pop
stack.append(s)
seen=[] #来保存放过的节点
seen.append(s)
while(len(stack)>0):
vertex=stack.pop() # 弹出最后一个元素
nodes=graph[vertex]
for node in nodes:
if node not in seen:
stack.append(node)
seen.append(node)
print(vertex) #把当前拿出去的节点打印出来
DFS(graph,"A")
Dijkstra
graph = {
"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
def init_distance(graph, startNode):
distance = {startNode : 0}
for vertex in graph:
if vertex != startNode:
distance[vertex] = float('inf')
return distance
def Dijkstra(graph, startNode):
pqueue = []
heapq.heappush(pqueue, (0, startNode))
seen = set()
parents = {startNode : None}
distance = init_distance(graph, startNode)
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))
parents[w] = vertex
distance[w] = dist + graph[vertex][w]
return parents, distance
parent , distance = Dijkstra(graph, "A")
print(parent)
print(distance)
网友评论