同步操作将从 编程语言算法集/Python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
"""pseudo-codeDIJKSTRA(graph G, start vertex s, destination vertex d)://all nodes initially unexplored1 - let H = min heap data structure, initialized with 0 and s [here 0 indicatesthe distance from start vertex s]2 - while H is non-empty:3 - remove the first node and cost of H, call it U and cost4 - if U has been previously explored:5 - go to the while loop, line 2 //Once a node is explored there is no needto make it again6 - mark U as explored7 - if U is d:8 - return cost // total cost from start to destination vertex9 - for each edge(U, V): c=cost of edge(U,V) // for V in graph[U]10 - if V explored:11 - go to next V in line 912 - total_cost = cost + c13 - add (total_cost,V) to HYou can think at cost as a distance where Dijkstra finds the shortest distancebetween vertices s and v in a graph G. The use of a min heap as H guaranteesthat if a vertex has already been explored there will be no other path withshortest distance, that happens because heapq.heappop will always return thenext vertex with the shortest distance, considering that the heap stores notonly the distance between previous vertex and current vertex but the entiredistance between each vertex that makes up the path from start vertex to targetvertex."""import heapqdef dijkstra(graph, start, end):"""Return the cost of the shortest path between vertices start and end.>>> dijkstra(G, "E", "C")6>>> dijkstra(G2, "E", "F")3>>> dijkstra(G3, "E", "F")3"""heap = [(0, start)] # cost from start node,end nodevisited = set()while heap:(cost, u) = heapq.heappop(heap)if u in visited:continuevisited.add(u)if u == end:return costfor v, c in graph[u]:if v in visited:continuenext = cost + cheapq.heappush(heap, (next, v))return -1G = {"A": [["B", 2], ["C", 5]],"B": [["A", 2], ["D", 3], ["E", 1], ["F", 1]],"C": [["A", 5], ["F", 3]],"D": [["B", 3]],"E": [["B", 4], ["F", 3]],"F": [["C", 3], ["E", 3]],}r"""Layout of G2:E -- 1 --> B -- 1 --> C -- 1 --> D -- 1 --> F\ /\\ ||----------------- 3 --------------------"""G2 = {"B": [["C", 1]],"C": [["D", 1]],"D": [["F", 1]],"E": [["B", 1], ["F", 3]],"F": [],}r"""Layout of G3:E -- 1 --> B -- 1 --> C -- 1 --> D -- 1 --> F\ /\\ ||-------- 2 ---------> G ------- 1 ------"""G3 = {"B": [["C", 1]],"C": [["D", 1]],"D": [["F", 1]],"E": [["B", 1], ["G", 2]],"F": [],"G": [["F", 1]],}shortDistance = dijkstra(G, "E", "C")print(shortDistance) # E -- 3 --> F -- 3 --> C == 6shortDistance = dijkstra(G2, "E", "F")print(shortDistance) # E -- 3 --> F == 3shortDistance = dijkstra(G3, "E", "F")print(shortDistance) # E -- 2 --> G -- 1 --> F == 3if __name__ == "__main__":import doctestdoctest.testmod()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。