📅  最后修改于: 2023-12-03 14:58:37.471000             🧑  作者: Mango
这道题是一道简单的图论问题,在给定的图中找出连接两个特定节点的最短路径。
我们可以使用经典的 Dijkstra 算法来计算最短路径。该算法是一种贪心算法,它会从起点开始不断扩展最短路径,直到到达目标节点。
Dijkstra 算法需要一个优先队列来存储待扩展的节点。每次从队列中取出与起点距离最短的节点,并扩展它的邻居节点。如果邻居节点未被访问过,则将它加入队列,并更新它到起点的距离值。
以下是 Dijkstra 算法的 Python 代码实现:
def dijkstra(graph, start, end):
# 初始化距离字典和队列
dist = {node: float('inf') for node in graph}
dist[start] = 0
queue = [(start, 0)]
while queue:
# 取出距离最短的节点
curr, curr_dist = queue.pop(0)
# 如果到达目标节点,则返回距离
if curr == end:
return curr_dist
# 扩展邻居节点
for neighbor, weight in graph[curr].items():
new_dist = curr_dist + weight
if new_dist < dist[neighbor]:
dist[neighbor] = new_dist
queue.append((neighbor, new_dist))
# 如果无法到达目标节点,则返回 -1
return -1
在计算最短路径之前,我们需要先将输入数据转化为图数据结构。这里我们可以使用 Python 的字典数据结构,将每个节点映射到它的邻居节点和边权重。
以下是构建图的 Python 代码实现:
def build_graph(n, m, edges):
# 构建空图
graph = {i: {} for i in range(1, n+1)}
# 添加边
for a, b, w in edges:
graph[a][b] = w
graph[b][a] = w
return graph
将上述代码组合起来,就可以得到完整的 Python 解答:
def dijkstra(graph, start, end):
# 初始化距离字典和队列
dist = {node: float('inf') for node in graph}
dist[start] = 0
queue = [(start, 0)]
while queue:
# 取出距离最短的节点
curr, curr_dist = queue.pop(0)
# 如果到达目标节点,则返回距离
if curr == end:
return curr_dist
# 扩展邻居节点
for neighbor, weight in graph[curr].items():
new_dist = curr_dist + weight
if new_dist < dist[neighbor]:
dist[neighbor] = new_dist
queue.append((neighbor, new_dist))
# 如果无法到达目标节点,则返回 -1
return -1
def build_graph(n, m, edges):
# 构建空图
graph = {i: {} for i in range(1, n+1)}
# 添加边
for a, b, w in edges:
graph[a][b] = w
graph[b][a] = w
return graph
# 读取输入数据
n, m = map(int, input().split())
edges = [list(map(int, input().split())) for _ in range(m)]
a, b = map(int, input().split())
# 构建图并计算最短路径
graph = build_graph(n, m, edges)
shortest_path = dijkstra(graph, a, b)
# 输出结果
print(shortest_path)
以上就是完整的解答。