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

Python迷宫路径查找函数找到路径仍返回False问题排查

迷宫求解程序问题定位

核心错误点

  • 递归返回值未透传:findPaths的四个方向递归调用结果没有被接收和返回,函数执行完毕后默认返回None,布尔判断时被识别为False,是问题的核心诱因。
  • 向上移动的边界条件错误:当前向上走的判断条件为i < 0,该条件永远无法命中,直接导致向上移动的逻辑完全失效。
  • 路径打印不完整(非必现错误):触发终点判断逻辑时,当前节点还未被加入路径列表,打印的结果会缺失终点D。
  • 潜在依赖错误:代码中使用了randint但没有导入random模块,运行时会直接抛出名称错误,需要在代码开头添加import random,并将所有randint替换为random.randint。

修复后的核心函数代码

def findPaths(m,path,i,j):
    r,c = len(m), len(m[0])
    if i == r-1 and j == c-1:
        # 补充终点到路径中
        path.append(m[i][j])
        print(path)
        path.pop()
        return True

    path.append(m[i][j])
    has_path = False
    # 向下移动
    if  i != r-1 and m[i+1][j] == '↓ ':
        has_path = has_path or findPaths(m,path,i+2,j)

    # 向上移动,修复边界判断
    if i >= 1 and m[i-1][j] == '↑ ':
        has_path = has_path or findPaths(m,path,i-2,j)

    # 向右移动
    if j != c-1 and m[i][j+1] == '→':
        has_path = has_path or findPaths(m,path,i,j+2)

    # 向左移动
    if j > 0 and m[i][j-1] == '←':
        has_path = has_path or findPaths(m,path,i,j-2)

    path.pop()
    # 向上返回是否找到路径的结果
    return has_path

替换原代码中的findPaths函数、补全random依赖即可解决始终返回False的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:24:00