You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于已实现的Dijkstra算法获取指定节点的距离?

Retrieve Specific Node Distance from Dijkstra's Results

Hey there! Looks like you've already got a working Dijkstra's algorithm that spits out a distance dictionary mapping each node to its shortest distance from the source. To make it easy to fetch a single node's distance, here's a straightforward approach:

First, let's finish up that Dijkstra function you started (since the code snippet cut off) to ensure we get the correct distance dictionary:

import heapq

graph = {
    '0': {'1': 2, '2': 5},
    '1': {'2': 3},
    '2': {'3': 4},
    '3': {'0': 21, '1': 8},
}

def di(graph, source):
    priority_queue = []
    heapq.heappush(priority_queue, (0, source))
    distances = {node: float('inf') for node in graph}
    distances[source] = 0
    visited = set()

    while priority_queue:
        current_distance, current_node = heapq.heappop(priority_queue)
        if current_node in visited:
            continue
        visited.add(current_node)
        for neighbor, weight in graph[current_node].items():
            distance = current_distance + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(priority_queue, (distance, neighbor))
    return distances

# Generate the full distance dictionary first
distance_results = di(graph, '0')  # This returns {'0': 0, '1': 2, '2': 5, '3': 9}

Now, create a simple function to fetch the distance for a specific node. We'll add a safety check to handle cases where the input node doesn't exist in our results:

def get_node_distance(distance_dict, target_node):
    if target_node not in distance_dict:
        raise ValueError(f"Node '{target_node}' doesn't exist in the distance results.")
    return distance_dict[target_node]

# Example usage
print(get_node_distance(distance_results, '3'))  # Output: 9
print(get_node_distance(distance_results, '1'))  # Output: 2

Quick Tips:

  • We run the Dijkstra algorithm once to generate the full distance dictionary—no need to re-run it every time you need a single node's distance, which saves computation time.
  • If you prefer not to raise an error for invalid nodes, you can adjust the function to return a default value like None or a user-friendly message instead.

内容的提问来源于stack exchange,提问作者Ria Dunn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:55:48