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

AI搜索程序未输出预期搜索结果,请求故障原因排查

分析你的AI搜索程序故障原因

我帮你排查了代码里的几个关键问题,正是这些错误导致程序输出fail和None:

  • 索引取值完全错误:你从open列表弹出元素后,对x、y、g的索引逻辑乱了。open里的元素格式是[g, x, y],正确的取值应该是:

    g = next[0]
    x = next[1]
    y = next[2]
    

    而你写的x = next[3]、y = next[4]会直接触发索引越界(每个元素只有3个值),这会让后续的位置判断完全失效,程序根本没法正确探索路径。

  • 边界判断逻辑错误:检查新位置y2的合法性时,你用了y2 < len(grid),但len(grid)是网格的行数,列数应该用len(grid[0]),正确的条件是:

    if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]):
    

    这个错误会让程序把右侧的合法路径误判为越界,直接堵死了到达终点的可能。

  • 函数无返回值:你的search()函数最后没有任何return语句,所以调用print search()时,Python会默认输出None。另外found = next的写法也不对,found是布尔标记,应该在找到终点时设为True,同时保存结果。

  • Python版本语法问题:如果用Python 3运行,print 'fail'这种写法会报错,需要改成print('fail')——不过你说程序输出了fail,应该是用Python 2运行的,还是建议统一成兼容写法。


修正后的完整代码

grid = [[0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 0]]
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
cost = 1
delta = [[-1, 0], # go up
         [ 0,-1], # go left
         [ 1, 0], # go down
         [ 0, 1]] # go right
delta_name = ['^', '<', 'v', '>']

def search():
    closed = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
    closed[init[0]][init[1]] = 1
    x = init[0]
    y = init[1]
    g = 0
    open = [[g, x, y]]
    found = False
    resign = False
    result = None  # 用来保存找到的终点结果

    while not found and not resign:
        if len(open) == 0:
            resign = True
            print('fail')
        else:
            open.sort()
            open.reverse()
            next_node = open.pop()  # 换变量名避免和内置next冲突
            g = next_node[0]
            x = next_node[1]
            y = next_node[2]

            if x == goal[0] and y == goal[1]:
                found = True
                result = next_node
                print(f"找到终点,总代价: {g}, 位置: [{x}, {y}]")
            else:
                for i in range(len(delta)):
                    x2 = x + delta[i][0]
                    y2 = y + delta[i][1]
                    # 修正边界判断逻辑
                    if 0 <= x2 < len(grid) and 0 <= y2 < len(grid[0]):
                        if closed[x2][y2] == 0 and grid[x2][y2] == 0:
                            g2 = g + cost
                            open.append([g2, x2, y2])
                            closed[x2][y2] = 1
    return result

print(search())

运行修正后的代码,就能正确找到从起点[0,0]到终点[4,5]的路径,输出结果类似找到终点,总代价: 11, 位置: [4, 5],最后打印的返回值是[11, 4, 5]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:03:19