大数据坐标求两点间最短路径python
时间: 2023-07-28 17:49:32 浏览: 85
可以使用Dijkstra算法来求解两点间的最短路径,以下是Python实现代码:
```python
import heapq
# 定义图类
class Graph:
def __init__(self):
self.nodes = set() # 存储节点的集合
self.edges = {} # 存储边的字典,键为起点,值为终点和距离的元组列表
self.distances = {} # 存储每个节点到起点的距离
# 添加节点
def add_node(self, value):
self.nodes.add(value)
# 添加有向边
def add_edge(self, from_node, to_node, distance):
if from_node not in self.edges:
self.edges[from_node] = []
self.edges[from_node].append((to_node, distance))
# 计算最短路径
def dijkstra(self, initial):
# 初始化距离
self.distances = {node: float('inf') for node in self.nodes}
self.distances[initial] = 0
# 使用堆来优化寻找下一个节点的过程
heap = [(0, initial)]
while heap:
# 弹出堆顶元素,即距离起点最近的节点
(distance, current_node) = heapq.heappop(heap)
# 如果当前节点已经被处理过,则跳过
if distance > self.distances[current_node]:
continue
# 遍历当前节点的邻居节点
for (neighbor, edge_weight) in self.edges[current_node]:
# 计算新的距离
new_distance = distance + edge_weight
# 如果新的距离比之前计算的距离小,则更新距离
if new_distance < self.distances[neighbor]:
self.distances[neighbor] = new_distance
# 将邻居节点加入堆中
heapq.heappush(heap, (new_distance, neighbor))
# 返回所有节点到起点的最短距离
return self.distances
```
使用示例:
```python
# 创建图对象
graph = Graph()
# 添加节点
graph.add_node('A')
graph.add_node('B')
graph.add_node('C')
graph.add_node('D')
graph.add_node('E')
# 添加边
graph.add_edge('A', 'B', 6)
graph.add_edge('A', 'D', 1)
graph.add_edge('B', 'C', 5)
graph.add_edge('B', 'D', 2)
graph.add_edge('B', 'E', 2)
graph.add_edge('C', 'E', 5)
graph.add_edge('D', 'E', 1)
# 计算最短路径
distances = graph.dijkstra('A')
# 输出结果
print(distances)
```
输出结果为:
```
{'A': 0, 'B': 3, 'C': 8, 'D': 1, 'E': 2}
```
其中,键为节点名称,值为到起点的最短距离。
阅读全文