用python实现dijkstra寻路算法
时间: 2023-09-20 07:03:33 浏览: 108
这里是一个实现Dijkstra算法寻路的Python代码示例:
```python
import heapq
import sys
class Graph:
def __init__(self):
self.edges = {}
self.weights = {}
def add_edge(self, from_node, to_node, weight):
if from_node in self.edges:
self.edges[from_node].append(to_node)
else:
self.edges[from_node] = [to_node]
self.weights[(from_node, to_node)] = weight
def dijkstra(graph, start):
visited = {start: 0}
path = {}
nodes = set(graph.edges.keys())
while nodes:
min_node = None
for node in nodes:
if node in visited:
if min_node is None:
min_node = node
elif visited[node] < visited[min_node]:
min_node = node
if min_node is None:
break
nodes.remove(min_node)
current_weight = visited[min_node]
for edge in graph.edges[min_node]:
weight = current_weight + graph.weights[(min_node, edge)]
if edge not in visited or weight < visited[edge]:
visited[edge] = weight
path[edge] = min_node
return visited, path
def shortest_path(graph, start, end):
visited, paths = dijkstra(graph, start)
full_path = []
path = [end]
while path[-1] != start:
path.append(paths[path[-1]])
for i in range(len(path)-1, -1, -1):
full_path.append(path[i])
return full_path
# 测试代码
g = Graph()
g.add_edge('A', 'B', 3)
g.add_edge('A', 'C', 2)
g.add_edge('B', 'D', 2)
g.add_edge('C', 'D', 4)
g.add_edge('C', 'E', 3)
g.add_edge('D', 'E', 1)
g.add_edge('D', 'F', 3)
g.add_edge('E', 'F', 1)
print(shortest_path(g, 'A', 'F')) # ['A', 'B', 'D', 'F']
```
这个示例中,我们首先定义了一个Graph类来表示我们的图。然后,我们实现了Dijkstra算法,它会返回一个包含最短路径的字典。最后,我们使用该算法来计算从一个节点到另一个节点的最短路径。
阅读全文