狄克斯拉算法
逻辑分析:
1: 找出最便宜的的节点,可在短时间内前往的节点 2: 对于该节点的邻居检查是否有其他节点,如果有就更新开销 3:重复这个过程直到对图中的所有节点都这样做 4:计算最终路径
用于解决的问题
1.从A出发是否存在到达B的路径; 2.从A出发到达B的最短路径(时间最少、或者路径最少等),事实上最后计算完成后,已经得到了A到各个节点的最短路径了;
#把所有的节点的邻居都存储在grash里面
graph = {}
graph["Start"] = {}
graph["Start"]["A"] = 6
graph["Start"]["B"] = 2
graph["A"] = {}
graph["A"]["End"] = 4
graph["B"] = {}
graph["B"]["C"] = 1
graph["B"]["End"] = 7
graph["C"] = {}
graph["C"]["A"] = 4
graph["C"]["End"] = 5
#infinity代表无穷大(或者未知)
infinity = float("inf")
#costs 代表所有的权重
costs = {}
costs["A"] = 6
costs["B"] = 2
costs["C"] = infinity
costs["End"] = infinity
#用来存储父节点
parents = {}
parents["A"] = "Start"
parents["B"] = "Start"
parents["C"] = None
parents["End"] = None
#用来记录处理过的节点
processed = []
#在未处理的节点里面找出开销最小的节点
def findLowestCostNode(costs, processed):
lowest_cost = infinity
lowest_cost_node = None
for node in costs.keys():
cost = costs[node]
if cost < lowest_cost and node not in processed: #每次找到最小的并且并不存在在poressed里面
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
def getResult():
node = findLowestCostNode(costs, processed) #节点
while node is not None and node != "End":
cost = costs[node] # 获取开销
print(node)
neighbors = graph[node]
for n in neighbors.keys():
new_cost = cost + neighbors[n]
if new_cost < costs[n]:
costs[n] = new_cost
parents[n] = node
processed.append(node)
node = findLowestCostNode(costs, processed)
if __name__ == '__main__':
getResult()
print(costs)
print(parents)