编写程序计算从“0”结点到其他结点的最短距离。
时间: 2023-09-23 16:11:07 浏览: 44
这个问题可以使用 Dijkstra 算法来解决。下面是 Python 代码实现:
```python
import heapq
def dijkstra(graph, start):
# 初始化距离字典
distances = {node: float('inf') for node in graph}
distances[start] = 0
# 初始化堆
heap = [(0, start)]
while heap:
# 取出距离最小的结点
(current_distance, current_node) = heapq.heappop(heap)
# 如果已经找到当前结点的最短路径,则继续下一个结点
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(heap, (distance, neighbor))
return distances
```
其中,`graph` 是一个字典,用来表示图结构,`start` 是起始结点。字典的 key 表示结点,value 是一个字典,表示该结点的邻居结点以及两结点之间的距离。
例如,下面的代码创建了一个有向图:
```python
graph = {
'0': {'1': 5, '2': 3},
'1': {'3': 6},
'2': {'1': 2, '3': 7},
'3': {'4': 4},
'4': {'3': 2}
}
```
运行 `dijkstra(graph, '0')` 就可以得到从结点 "0" 到其他结点的最短距离。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)