写一段迪杰斯特拉算法的代码
时间: 2023-09-22 09:06:48 浏览: 113
迪杰斯特拉算法代码实现
5星 · 资源好评率100%
### 回答1:
答:def dijkstra(graph,start,target):
shortest_distance={}
predecessor={}
unseenNodes=graph
infinity=999999
path=[]
for node in unseenNodes:
shortest_distance[node]=infinity
shortest_distance[start]=0 while unseenNodes:
minNode=None
for node in unseenNodes:
if minNode is None:
minNode=node
elif shortest_distance[node]<shortest_distance[minNode]:
minNode=node for childNode, weight in graph[minNode].items():
if weight+shortest_distance[minNode]<shortest_distance[childNode]:
shortest_distance[childNode]=weight+shortest_distance[minNode]
predecessor[childNode]=minNode
unseenNodes.pop(minNode) currentNode=target
while currentNode!=start:
try:
path.insert(0,currentNode)
currentNode=predecessor[currentNode]
except KeyError:
print('Path not reachable')
break
path.insert(0,start)
if shortest_distance[target] != infinity:
print('Shortest distance is '+str(shortest_distance[target]))
print('And the path is '+str(path))dijkstra(graph, 'A', 'B')
### 回答2:
迪杰斯特拉算法用于在带有权重的有向图中找到从源节点到目标节点的最短路径。这段代码实现了迪杰斯特拉算法。
```
# 定义有向图
graph = {
'A': {'B': 5, 'C': 2},
'B': {'D': 3},
'C': {'B': 1, 'D': 6},
'D': {'E': 2},
'E': {}
}
# 定义无穷大距离
inf = float('inf')
def dijkstra(graph, start, end):
# 初始化距离字典,设定起点距离为0,其余节点距离为无穷大
distances = {node: inf for node in graph}
distances[start] = 0
# 初始化父节点字典
parents = {}
# 初始化待访问节点集合
unvisited_nodes = set(graph.keys())
while unvisited_nodes:
# 找出当前距离最短的节点
current_node = min(unvisited_nodes, key=lambda node: distances[node])
# 如果找到目标节点,则构建最短路径并返回
if current_node == end:
shortest_path = []
while current_node in parents:
shortest_path.append(current_node)
current_node = parents[current_node]
shortest_path.append(start)
shortest_path.reverse()
return shortest_path
# 移除当前节点
unvisited_nodes.remove(current_node)
# 更新与当前节点相邻节点的距离
for neighbor, weight in graph[current_node].items():
if distances[current_node] + weight < distances[neighbor]:
distances[neighbor] = distances[current_node] + weight
parents[neighbor] = current_node
# 如果无法找到最短路径,则返回空列表
return []
# 测试
start_node = 'A'
end_node = 'E'
shortest_path = dijkstra(graph, start_node, end_node)
if len(shortest_path) > 0:
print(f"The shortest path from {start_node} to {end_node}: {' -> '.join(shortest_path)}")
else:
print(f"Cannot find a path from {start_node} to {end_node}")
```
以上代码实现了迪杰斯特拉算法,通过构建最短路径的父节点字典来记录每个节点的父节点,并在找到最短路径后返回路径列表。
### 回答3:
迪杰斯特拉算法是一种用于求解单源最短路径的算法。以下是一段示例代码:
```python
import sys
def dijkstra(graph, start):
# 初始化距离字典,记录每个节点到起点的最短距离
dist = {}
for node in graph:
dist[node] = sys.maxsize
dist[start] = 0
# 初始化已访问节点的集合和未访问节点的集合
visited = set()
unvisited = set(graph.keys())
while unvisited:
# 选择当前距离起点最短的节点
current = None
for node in unvisited:
if current is None or dist[node] < dist[current]:
current = node
# 如果当前节点为终点,则跳出循环
if current == end:
break
# 访问当前节点,并更新与其邻居节点的距离
unvisited.remove(current)
visited.add(current)
for neighbor in graph[current]:
if neighbor not in visited:
new_dist = dist[current] + graph[current][neighbor]
if new_dist < dist[neighbor]:
dist[neighbor] = new_dist
return dist
# 示例使用
graph = {
'A': {'B': 5, 'C': 3},
'B': {'A': 5, 'C': 1, 'D': 3},
'C': {'A': 3, 'B': 1, 'D': 2, 'E': 6},
'D': {'B': 3, 'C': 2, 'E': 4, 'F': 6},
'E': {'C': 6, 'D': 4, 'F': 2},
'F': {'D': 6, 'E': 2}
}
start = 'A'
end = 'F'
distances = dijkstra(graph, start)
shortest_distance = distances[end]
print(f"The shortest distance from {start} to {end} is: {shortest_distance}")
```
以上代码演示了一个简单的有向加权图的使用情景。根据给定的图和起点,使用迪杰斯特拉算法求解出起点到终点的最短路径距离,并打印出结果。
阅读全文