请给出使用Dijkstra算法解决农夫过河问题的代码
时间: 2024-12-03 11:12:00 浏览: 17
好的,农夫过河问题是经典的图论问题,可以使用Dijkstra算法来找到最短路径。这里我们假设有一条河,农夫需要借助渡船每次只能带一定重量的食物过河,每种食物有自己的重量。以下是用Python实现的一个简化版Dijkstra算法:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('infinity') for node in graph}
distances[start] = 0
queue = [(0, start)]
while queue:
current_distance, current_node = heapq.heappop(queue)
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(queue, (distance, neighbor))
return distances
# 示例图(这里只是一个简单表示,实际可能更复杂)
graph = {
'A': {'B': 1},
'B': {'C': 2, 'D': 5},
'C': {},
'D': {'E': 3},
'E': {}
}
start_node = 'A'
shortest_paths = dijkstra(graph, start_node)
for node, path_length in shortest_paths.items():
print(f"从{start_node}到{node}的最短距离是: {path_length}")
阅读全文