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

如何遍历可变长度路径至同一终点?有向图指定路径提取BFS适配问题

解决方案:适配BFS提取指定长度的起点终点相同路径

Got it, I totally get why standard BFS code isn't cutting it here—most off-the-shelf implementations focus on shortest paths or unconstrained path finding, but you need to zero in on exactly 4-edge and 5-edge paths that start and end at node B. Let's adapt BFS to fit this specific requirement step by step.

核心思路

The key tweak here is to track more state in our BFS queue than just the current node. We need to keep tabs on:

  • The current node we're visiting
  • The full path taken to get here
  • The number of edges (path length) used so far

With this extra state, we can:

  1. Stop extending a path once its length exceeds our maximum target (5 edges)
  2. Check if a path hits our target conditions (length is 4 or 5, ends at B) and add it to our results immediately

代码实现(附示例)

Let's use Python with an adjacency list to represent your directed network (I've built it to match your sample paths):

# 定义示例有向网络的邻接表
graph = {
    'B': ['C', 'A', 'B'],
    'C': ['B'],
    'A': ['B']
}

def find_target_paths(graph, start_node, target_lengths):
    result_paths = []
    # 初始化BFS队列:(当前节点, 已走路径, 当前路径长度)
    queue = [(start_node, [start_node], 0)]
    
    while queue:
        current, path, current_length = queue.pop(0)  # BFS用FIFO队列
        
        # 检查是否符合目标条件:路径长度在指定列表中,且终点是起点B
        if current_length in target_lengths and current == start_node:
            result_paths.append(path)
        
        # 只继续扩展未达到最大目标长度的路径
        if current_length < max(target_lengths):
            for neighbor in graph.get(current, []):
                # 复制路径避免引用修改问题
                new_path = path.copy()
                new_path.append(neighbor)
                queue.append((neighbor, new_path, current_length + 1))
    
    return result_paths

# 调用函数,提取长度为4和5的路径
targets = {4, 5}
all_matching_paths = find_target_paths(graph, 'B', targets)

# 按长度分类输出结果
print("4长度路径:")
for path in all_matching_paths:
    if len(path) - 1 == 4:  # 路径节点数 = 边数 + 1
        print("--".join(path))

print("\n5长度路径:")
for path in all_matching_paths:
    if len(path) - 1 == 5:
        print("--".join(path))

关键细节说明

  • 状态跟踪: By storing the full path and current length in the queue, we never lose track of how we got to a node or how long the journey was. This is crucial for filtering paths by exact length.
  • 避免无限循环: Even though your graph has cycles (like B → B), we cap the maximum path length at 5, so the BFS will naturally terminate without looping forever.
  • 路径复制: We use path.copy() when creating new paths to prevent all queue entries from sharing the same list reference—this ensures each path in the result is unique and correct.

注意事项

  • If your actual directed network is large, you can optimize memory by avoiding storing the full path (if you only need to count paths instead of listing them). But since you need the actual path strings, storing the full path is necessary.
  • Adjust the graph adjacency list to match your real network structure—make sure every node's outgoing edges are correctly listed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:19:24