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

如何在递归DFS函数中操作并返回字符串形式的遍历路径?

问题分析与解决方案

问题根源

  1. 字符串不可变性:Python中字符串是不可变类型,output += str(starting_node)会生成新的字符串对象,递归调用时传递的是原字符串的副本,下层函数修改后的结果不会同步到上层,最终只返回初始添加的"1"。
  2. 冗余的visited标记:在循环内提前标记visited[vertex] = True是多余的,因为进入dfs函数时已经执行了该操作,且可能导致逻辑混乱。
  3. 路径格式缺失:原代码直接拼接节点字符串,没有添加空格,无法得到期望的带空格分隔格式。

修正方案1:递归返回拼接后的路径字符串

利用递归函数返回子路径,将其拼接到当前节点的字符串后,解决不可变对象的传递问题:

adj_lst = [None, [3, 4], [3], [1, 2], [1]]
size = len(adj_lst)
visited = [False] * size

def dfs(starting_node, a_lst):
    visited[starting_node] = True
    output = str(starting_node)
    for vertex in a_lst[starting_node]:
        if not visited[vertex]:
            child_path = dfs(vertex, a_lst)
            output += " " + child_path
    return output

print(dfs(1, adj_lst))  # 输出:1 3 2 4

修正方案2:使用可变列表存储路径

借助列表(可变对象)收集节点,最后统一格式化为字符串,更直观高效:

adj_lst = [None, [3, 4], [3], [1, 2], [1]]
size = len(adj_lst)
visited = [False] * size

def dfs(starting_node, a_lst, path):
    visited[starting_node] = True
    path.append(str(starting_node))
    for vertex in a_lst[starting_node]:
        if not visited[vertex]:
            dfs(vertex, a_lst, path)

path = []
dfs(1, adj_lst, path)
print(" ".join(path))  # 输出:1 3 2 4

内容的提问来源于stack exchange,提问作者Mosheur Rahman Wolied

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:15:38