标签:获取 ide class play des cos closed one heap
本章内容:
7.1狄克斯特拉算法
4个步骤:
7.3负边权
狄克斯特拉算法不支持包含负边权的图,因为,狄克斯特拉算法这样假设:对于处理过的海报节点,没有前往该节点的更短的路径。包含负边权的图,可使用贝尔曼-福德算法(bellman-Ford algorithm)。
7.4实现
1 # the graph 2 graph = {} 3 graph["start"] = {} 4 graph["start"]["a"] = 6 5 graph["start"]["b"] = 2 6 7 graph["a"] = {} 8 graph["a"]["fin"] = 1 9 10 graph["b"] = {} 11 graph["b"]["a"] = 3 12 graph["b"]["fin"] = 5 13 14 graph["fin"] = {} 15 16 # the costs table 17 infinity = float("inf") 18 costs = {} 19 costs["a"] = 6 20 costs["b"] = 2 21 costs["fin"] = infinity 22 23 # the parents table 24 parents = {} 25 parents["a"] = "start" 26 parents["b"] = "start" 27 parents["fin"] = None 28 29 processed = [] 30 31 def find_lowest_cost_node(costs): 32 lowest_cost = float("inf") 33 lowest_cost_node = None 34 # Go through each node. 35 for node in costs: 36 cost = costs[node] 37 # If it‘s the lowest cost so far and hasn‘t been processed yet... 38 if cost < lowest_cost and node not in processed: 39 # ... set it as the new lowest-cost node. 40 lowest_cost = cost 41 lowest_cost_node = node 42 return lowest_cost_node 43 44 # Find the lowest-cost node that you haven‘t processed yet. 45 node = find_lowest_cost_node(costs) 46 # If you‘ve processed all the nodes, this while loop is done. 47 while node is not None: 48 cost = costs[node] 49 # Go through all the neighbors of this node. 50 neighbors = graph[node] 51 for n in neighbors.keys(): 52 new_cost = cost + neighbors[n] 53 # If it‘s cheaper to get to this neighbor by going through this node... 54 if costs[n] > new_cost: 55 # ... update the cost for this node. 56 costs[n] = new_cost 57 # This node becomes the new parent for this neighbor. 58 parents[n] = node 59 # Mark the node as processed. 60 processed.append(node) 61 # Find the next node to process, and loop. 62 node = find_lowest_cost_node(costs) 63 64 print "Cost from the start to each node:" 65 print costs
字典graph描述了一个图,如下所示:
costs描述了每个节点的开销;
parents描述了一个父节点散列表。
算法逻辑简述如下:
7.6小结
标签:获取 ide class play des cos closed one heap
原文地址:https://www.cnblogs.com/mofei004/p/8893414.html