2018-05-07
2018-05-07 本文已影响0人
木马音响积木
p116 算法图解,7.1 作业,答案,给大家参看
graph = {}
graph["start"] = {}
graph["start"]["a"] = 5
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["c"] = 4
graph["a"]["d"] = 2
graph["b"] = {}
graph["b"]["a"] = 8
graph["b"]["d"] = 7
#graph["b"]["fin"] = 5
graph["c"] = {}
graph["c"]["fin"] = 3
graph["c"]["d"] = 6
graph["d"] = {}
graph["d"]["fin"] = 1
graph["fin"] = {}
# costs
infinity = float("inf")
costs = {}
costs["a"] = 5
costs["b"] = 2
costs["c"] = infinity
costs["d"] = infinity
costs["fin"] = infinity
# parent
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
# processe
processed = []
#find_lowes
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
#Dijkstra implement
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)
#print(processed)
theway=[]
#print(parents["fin"] )
hh=1
lala = parents["fin"]
theway.append("fin")
theway.append(lala)
while lala != "start" and hh<500: # to Avoid dead loops
lala =parents[lala]
# print(lala)
hh+=7
#print(hh)
theway.append(lala)
theway.reverse()
print(theway)
print('the lowest cost is '+str(costs["fin"]) )
结果
$python main.py
['start', 'a', 'd', 'fin']
the lowest cost is 8