# the graph
graph = {}#创建一个散列表存储节点的所有邻居
graph["start"] = {}#创建另外的一个散列表,存储start节点到其他边的权重
graph["start"]["a"] = 6
graph["start"]["b"] = 2
#要获取起点的所有邻居,可像下面这样做。
#>>> print graph["start"].keys()
#["a", "b"]
graph["a"] = {}
graph["a"]["fin"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5
graph["fin"] = {}#终点没有任何邻居
# the costs table
#你不知道到终点需要多长时间。对于还不知道的开销,你将其设 置为无穷大。
#在Python中能够表示无穷大吗?你可以这样做: infinity = float("inf")
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity
# the parents table
#存储父节点的散列表
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
processed = []
#用一个数组来记录处理过的节点
#函数find_lowest_cost_node找出开销最低的节点
def find_lowest_cost_node(costs):
lowest_cost = float("inf")
lowest_cost_node = None
# Go through each node.
for node in costs:#遍历所有的节点
cost = costs[node]
# If it's the lowest cost so far and hasn't been processed yet...
if cost < lowest_cost and node not in processed:
#如果当前节点的开销更低且未处理过,
# ... set it as the new lowest-cost node.
lowest_cost = cost
#就将其视为开销最低的节点。
lowest_cost_node = node
return lowest_cost_node
# Find the lowest-cost node that you haven't processed yet.
node = find_lowest_cost_node(costs)
#在未处理的节点中找出开销最小的节点;
# If you've processed all the nodes, this while loop is done.
while node is not None:#这个while循环在所有节点都被处理后才结束。
cost = costs[node]
# Go through all the neighbors of this node.
neighbors = graph[node]
for n in neighbors.keys():#遍历当前节点的所有邻居
new_cost = cost + neighbors[n]
# If it's cheaper to get to this neighbor by going through this node...
#如果当前节点前往该邻居更近,则更新该邻居的开销。
if costs[n] > new_cost:
# ... update the cost for this node.
costs[n] = new_cost
# This node becomes the new parent for this neighbor.
parents[n] = node
#同时将该邻居的父节点设置为当前节点;
# Mark the node as processed.
processed.append(node)
#将当前节点标记为处理过
# Find the next node to process, and loop.
node = find_lowest_cost_node(costs)
#找出接下来要处理的节点,并循环
print ("Cost from the start to each node:")
print (costs)
输出:
Cost from the start to each node:
{'a': 5, 'b': 2, 'fin': 6}
#阿西吧,有些没看懂啊这一大串代码