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

基于Bellman-Ford算法的源点到负环无重复环最短路径技术问询

求源节点到负环的无重复环最短路径解决方案

我现在碰到了一个图算法相关的问题:想找到从源节点到负环的最短路径,而且要求路径里不能重复经过任何环。如果这个问题已经有成熟的解决方案,麻烦各位大佬指点一下;要是还没有确定解法,我之后会贴出自己的思路,希望大家帮忙找找错误。

先放一段我基于Networkx实现的Bellman-Ford算法检测负环的简化代码(这是算法的直接实现,后续会补充完整逻辑):

import networkx as nx

def detect_negative_cycle(G, source):
    # 初始化节点距离与前驱节点
    distance = {node: float('inf') for node in G.nodes()}
    distance[source] = 0
    predecessor = {node: None for node in G.nodes()}

    # 执行松弛操作
    for _ in range(len(G.nodes()) - 1):
        updated = False
        for u, v, data in G.edges(data=True):
            weight = data['weight']
            if distance[u] != float('inf') and distance[v] > distance[u] + weight:
                distance[v] = distance[u] + weight
                predecessor[v] = u
                updated = True
        if not updated:
            break

    # 检测并提取负环
    negative_cycle = []
    for u, v, data in G.edges(data=True):
        weight = data['weight']
        if distance[u] != float('inf') and distance[v] > distance[u] + weight:
            # 回溯找到环的起点
            cycle_node = v
            visited = set()
            while cycle_node not in visited:
                visited.add(cycle_node)
                cycle_node = predecessor[cycle_node]
            # 提取完整环结构
            cycle = []
            current = cycle_node
            while True:
                cycle.append(current)
                current = predecessor[current]
                if current == cycle_node:
                    cycle.append(current)
                    break
            negative_cycle = cycle[::-1]
            break
    return negative_cycle

目前这段代码只能检测到负环的存在,但还没完成从源节点到负环的最短路径筛选,而且完全不知道怎么处理“不重复经过任何环”的约束,求各位帮忙看看~


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:39:13