from collections import defaultdict
import sys
class Graph:
def __init__(self):
self.nodes = {} #节点集合
self.edges = defaultdict(list)
self.distances = {}
def add_node(self, node):
self.nodes.setdefault(node.name,node)
def add_edge(self, from_node, to_node, distance):
self.edges[from_node].append(to_node) #key为节点名称,value为[],每一个相邻的节点
self.distances[(from_node, to_node)] = distance# 两个节点之间的局里
class Node:
def __init__(self, name):
self.name = name # 节点名称
self.predecessor = None # 前向节点
self.distance = sys.maxsize # 默认的距离
def set_distance(self, dist):
self.distance = dist
def set_predecessor(self, pred):
self.predecessor = pred
def get_distance(self):
return self.distance
def get_predecessor(self):
return self.predecessor
def dijkstra(grath,initial,end):
permanent = set()
temporary = set()
temporary.add(initial)
grath.nodes[initial].set_distance(0)
while temporary:
min_node = None
for node in temporary:
if min_node is None:
min_node = grath.nodes[node]
elif grath.nodes[node].get_distance() < min_node.get_distance():
min_node = grath.nodes[node]
temporary.remove(min_node.name)
permanent.add(min_node.name)
for journode in grath.edges[min_node.name]:
new_distance = min_node.get_distance()+grath.distances[(min_node.name,journode)]
if journode not in permanent and grath.nodes[journode].get_distance() > new_distance:
grath.nodes[journode].set_distance(new_distance)
grath.nodes[journode].set_predecessor(min_node)
temporary.add(journode)
printpath(grath,end)
def printpath(grath,end):
current = end
path = list()
path.append(end)
while grath.nodes[current].get_predecessor() != None:
path.append(grath.nodes[current].get_predecessor().name)
current = grath.nodes[current].get_predecessor().name
# path = list(path)
# path.reverse()
print(path)
if __name__ == '__main__':
# 构建图
g = Graph()
a = Node("A")
g.add_node(a)
g.add_node(Node("B"))
g.add_node(Node("C"))
g.add_node(Node("D"))
g.add_node(Node("E"))
f = Node("F")
g.add_node(f)
g.add_edge("A", "B", 10)
g.add_edge("B", "A", 10)
g.add_edge("A", "C", 15)
g.add_edge("C", "A", 15)
g.add_edge("A", "E", 30)
g.add_edge("E", "A", 30)
g.add_edge("B", "E", 14)
g.add_edge("E", "B", 14)
g.add_edge("B", "D", 5)
g.add_edge("D", "B", 5)
g.add_edge("C", "E", 12)
g.add_edge("E", "C", 12)
g.add_edge("C", "D", 12)
g.add_edge("D", "C", 12)
g.add_edge("D", "F", 10)
g.add_edge("F", "D", 10)
g.add_edge("E", "F", 20)
g.add_edge("F", "E", 20)
dijkstra(g, "A", "D")
<<<
['D', 'B', 'A']
最短路径问题——DIJKSTRA算法
最新推荐文章于 2024-03-25 13:38:16 发布