You need to enable JavaScript to run this app. 递归函数返回None而非目标列表:字符矩阵查找字符串位置问题排查
优惠活动
大模型
产品
解决方案
定价
更多

递归函数返回None而非目标列表:字符矩阵查找字符串位置问题排查

问题原因与修正方案

现有代码核心问题

  • 语法错误:text[]写法非法,应为text[index];变量名拼写错误,indice应与参数名一致为index;next_row、next_col定义在encontrar_ocurrencias作用域内,busqueda函数无法直接访问。
  • 递归逻辑错误:遍历8个方向时直接return busqueda(...),会导致第一个方向搜索结束后直接终止函数,剩余7个方向完全不会被遍历,无法收集所有匹配路径。
  • 结果收集逻辑缺失:encontrar_ocurrencias函数没有定义总结果容器接收每次搜索的匹配路径,也没有return语句,调用后自然返回None。
  • 路径返回问题:找到匹配路径时直接返回引用,后续回溯操作修改path会导致已保存的路径被篡改。
  • 你之前把return换成print能输出正确结果,是因为直接在递归终止节点打印了当前匹配路径,不需要经过多层函数调用传递返回值;而用return时没有逐层收集子调用的返回结果,也没有在外层函数返回总结果,最终得到None。

修正后的完整代码

# 方向变量提取到全局作用域
next_row = [-1,-1,-1,0,0,1,1,1]
next_col = [-1,0,1,-1,1,-1,0,1]

def valid_move(x, y, path, cant_row, cant_col):
    return (0<=x<=cant_row-1) and (0<=y<=cant_col-1) and ((x,y) not in path)

def busqueda(soup, text, row, col, path, index):
    cant_row = len(soup)
    cant_col = len(soup[0])
    # 当前字符不匹配直接返回空列表
    if soup[row][col] != text[index]:
        return []
    # 匹配到最后一个字符,返回路径副本
    if index == len(text)-1:
        full_path = path.copy()
        full_path.append((row,col))
        return [full_path]
    # 当前节点入路径
    path.append((row,col))
    soluciones = []
    # 遍历所有方向收集所有匹配路径
    for move in range(8):
        new_x = row + next_row[move]
        new_y = col + next_col[move]
        if valid_move(new_x, new_y, path, cant_row, cant_col):
            sub_res = busqueda(soup, text, new_x, new_y, path, index+1)
            soluciones.extend(sub_res)
    # 回溯
    path.pop()
    return soluciones

def encontrar_ocurrencias(soup,text):
    cant_row = len(soup)
    cant_col = len(soup[0])
    path = []
    total_res = []
    # 遍历所有起点收集结果
    for i in range(cant_row):
        for j in range(cant_col):
            res = busqueda(soup, text, i, j, path, 0)
            if res:
                total_res.extend(res)
    return total_res

# 测试用例
soup = ["LAMXB","AOEYF","FCHTB","GFKAR","POSFD"]
text = "HOLA"
print(encontrar_ocurrencias(soup, text))

运行结果

输出与预期完全一致:

[[(2, 2), (1, 1), (0, 0), (0, 1)], [(2, 2), (1, 1), (0, 0), (1, 0)]]

内容的提问来源于stack exchange,提问作者José Ignacio Farías Olivares

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 16:06:03