Python写一个迪杰斯特拉算法
时间: 2023-09-16 18:05:02 浏览: 106
迪杰斯特拉算法
### 回答1:
好的,以下是Python实现的Dijkstra算法代码:
```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
```
这个函数接受一个图形的字典表示和起点,返回一个字典,其中包含从起点到每个节点的最短路径距离。在这个实现中,我们使用了一个堆来维护候选节点的顺序,这可以在某些情况下提高性能。
### 回答2:
迪杰斯特拉算法(Dijkstra's algorithm)是一种用于寻找加权有向图中从一个顶点到其他所有顶点的最短路径的算法。下面是用Python编写的迪杰斯特拉算法的示例代码:
```python
import sys
def dijkstra(graph, start):
# 初始化距离字典和访问标志字典
distance = {vertex: sys.maxsize for vertex in graph}
distance[start] = 0
visited = {}
while len(visited) < len(graph):
# 选取当前距离最小且未被访问的顶点
current_vertex = min({vertex: distance[vertex] for vertex in graph if vertex not in visited}, key=distance.get)
visited[current_vertex] = True
# 更新相邻顶点的最短距离
for neighbor_vertex, weight in graph[current_vertex].items():
new_distance = distance[current_vertex] + weight
if new_distance < distance[neighbor_vertex]:
distance[neighbor_vertex] = new_distance
return distance
# 测试
graph = {
'A': {'B': 5, 'C': 2},
'B': {'D': 4, 'E': 2},
'C': {'B': 8, 'E': 7},
'D': {'F': 3},
'E': {'D': 6, 'F': 1},
'F': {}
}
start_vertex = 'A'
shortest_distances = dijkstra(graph, start_vertex)
for vertex, distance in shortest_distances.items():
print(f'The shortest distance from {start_vertex} to {vertex} is {distance}.')
```
以上代码利用字典来表示有向图,其中字典的键是顶点,值是该顶点到相邻顶点的距离。函数`dijkstra`接受一个有向图和起始顶点作为输入,返回一个包含起始顶点到其他所有顶点的最短距离的字典。在示例中,我们使用一个简单的有向图进行测试,并输出起始顶点到其他顶点的最短距离。
### 回答3:
迪杰斯特拉算法是一种用于求解图中单源最短路径问题的算法。在Python中,我们可以使用以下代码实现迪杰斯特拉算法:
```python
import sys
class Dijkstra:
def __init__(self, vertices):
self.vertices = vertices
self.graph = [[0] * vertices for _ in range(vertices)]
def find_min_distance(self, distance, visited):
min_distance = sys.maxsize
for v in range(self.vertices):
if distance[v] < min_distance and not visited[v]:
min_distance = distance[v]
min_index = v
return min_index
def dijkstra_algorithm(self, start_vertex):
distance = [sys.maxsize] * self.vertices
distance[start_vertex] = 0
visited = [False] * self.vertices
for _ in range(self.vertices):
min_distance_vertex = self.find_min_distance(distance, visited)
visited[min_distance_vertex] = True
for v in range(self.vertices):
if self.graph[min_distance_vertex][v] > 0 and not visited[v] \
and distance[min_distance_vertex] != sys.maxsize \
and distance[min_distance_vertex] + self.graph[min_distance_vertex][v] < distance[v]:
distance[v] = distance[min_distance_vertex] + self.graph[min_distance_vertex][v]
for v in range(self.vertices):
print("Vertex:", v, "Distance:", distance[v])
if __name__ == '__main__':
graph = Dijkstra(6)
graph.graph = [[0, 2, 0, 0, 0, 0],
[2, 0, 4, 1, 0, 0],
[0, 4, 0, 6, 3, 0],
[0, 1, 6, 0, 0, 2],
[0, 0, 3, 0, 0, 5],
[0, 0, 0, 2, 5, 0]]
graph.dijkstra_algorithm(0)
```
这段代码首先定义了一个Dijkstra类,构造函数初始化了图的顶点个数和图的邻接矩阵。接下来,使用find_min_distance方法找到当前距离最小且未被访问的顶点,并将其标记为已访问。然后,通过遍历当前顶点的邻接顶点,更新最短距离。最后,输出每个顶点到起始顶点的最短距离。
在主程序中,创建一个Dijkstra对象,并设置图的邻接矩阵。然后调用dijkstra_algorithm方法来计算从起始顶点到其他顶点的最短距离。输出的结果格式为:顶点编号和对应的最短距离。
阅读全文