单源最短路径贪心算法为代码
时间: 2024-06-19 18:04:31 浏览: 120
单源最短路径贪心算法的思想是,从起点开始,每次选择当前距离最短的一个点作为中间点,更新其它点到起点的最短路径。这种算法适用于没有负权边的图。
以下是单源最短路径贪心算法的代码实现(以Dijkstra算法为例):
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
curr_distance, curr_node = heapq.heappop(pq)
if curr_distance > distances[curr_node]:
continue
for neighbor, weight in graph[curr_node].items():
distance = curr_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
```
其中,graph是一个字典,表示图的邻接表形式;start是起点。函数返回一个字典,表示每个点到起点的最短距离。
阅读全文