狄克斯特拉算法是用于在加权图中查找到最短路径的算法,所以你就需要找到从出发点到终止点的路径,比较出最短的一条,这是我们不妨利用逆向思维的方法,要想找到最短的终止节点,那么你就必须要是在它的上一个最短的节点(称为父节点),用相同的思想找到每个节点的父节点直到出发节点,所以我们要明确一下几点
1.怎么用代码讲图实现出来
2.怎么记录每个节点的开销(也就是节点到开始点的距离)
3.怎么表示父节点是什么
以下我将从这三方面出发,利用代码实现狄克斯特拉算法
# 用散列表实现图的关系
graph = {}
graph['start'] = {}
graph['start']['a']=6
graph['start']['b']=2
graph['a']={}
graph['a']['fin']=1
graph['b']={}
graph['b']['a']=3
graph['b']['fin']=5
graph['fin'] = {}
# 开销
costs={}
costs['a']=6
costs['b']=2
costs['fin']=float('inf')
# 父节点
parents={}
parents['a']='start'
parents['b']='start'
parents['fin']=None
# 处理访问过的节点
processed=[]
# 在未处理的点中找到开销最小的值
def find_lowest_cost_node(costs):
lowest_cost=float('inf')
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
# 找到最短路径
def find_shortset_path():
node='fin'
shortest_path=['end']
while node != 'start':
node = parents[node]
shortest_path.append(node)
shortest_path.reverse()
return shortest_path
if __name__ == '__main__':
node = find_lowest_cost_node(costs)
while node is not None:
cost = costs[node]
neighbors = graph[node]
for n in neighbors.keys():
new_cost = cost + neighbors[n]
if costs[n] > new_cost:
costs[n] = new_cost
parents[n] = node
processed.append(node)
node = find_lowest_cost_node(costs)
shortset_path = find_shortset_path()
print(shortset_path)