gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
你好
- User
你好
- Assistant
你好!有什么我可以帮助你的吗?
- User
写一段迪杰斯特拉算法的python代码
- Assistant
当然可以!迪杰斯特拉(Dijkstra)算法是一种用于计算单源最短路径的算法,适用于加权图。以下是一个简单的 Python 实现:
pythonimport heapq def dijkstra(graph, start): # 用于存储最短路径的字典,键是节点,值是从起点到该节点的最短距离 shortest_distances = {node: float('inf') for node in graph} shortest_distances[start] = 0 # 优先队列(heap),用于在计算过程中获取距离最短的节点 priority_queue = [(0, start)] while priority_queue: # 取出距离起点最近的节点 current_distance, current_node = heapq.heappop(priority_queue) # 如果当前节点的距离不是最短的,跳过 if current_distance > shortest_distances[current_node]: continue # 更新相邻节点的最短路径 for neighbor, weight in graph[current_node].items(): distance = current_distance + weight # 如果找到更短的路径,则更新并将该节点加入优先队列 if distance < shortest_distances[neighbor]: shortest_distances[neighbor] = distance heapq.heappush(priority_queue, (distance, neighbor)) return shortest_distances # 示例使用 graph = { 'A': {'B': 1, 'C': 4}, 'B': {'A': 1, 'C': 2, 'D': 5}, 'C': {'A': 4, 'B': 2, 'D': 1}, 'D': {'B': 5, 'C': 1} } start_node = 'A' print(dijkstra(graph, start_node))
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.