首页 > 解决方案 > AI 搜索程序不输出搜索矩阵

问题描述

编写并运行了一个 AI 搜索程序,从头到尾运行搜索或找到结果。但是,当我运行它时,我没有得到搜索结果,而是失败并且没有。任何想法可能是问题的原因将不胜感激


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
    
    while found is False and resign is False:
        if len(open) == 0:
            resign = True
            print 'fail'
            
        else:
            open.sort()
            open.reverse()
            next = open.pop()
            
            x = next[3]
            y = next[4]
            g = next[1]
           
            
            if x == goal[0] and y == goal[1]:
                found = next
                print next
            else:
                for i in range(len(delta)):
                    x2 = x + delta[i][0]
                    y2 = y + delta[i][1]
                    if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid):
                        if closed[x2][y2] == 0 and grid[x2][y2] == 0:
                            g2 = g + cost
                            
                            open.append([g2, x2, y2])
                            closed[x2][y2] = 1
print search()

标签: pythonsearchartificial-intelligence

解决方案


第一个问题出在这部分代码中:

x = next[3]
y = next[4]
g = next[1]

列表中的每个元素open只有三个条目,因此34是无效索引。这可能应该更改为:

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

第二个问题在这部分的第一行:

if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid):
    if closed[x2][y2] == 0 and grid[x2][y2] == 0:
        g2 = g + cost

两者x2y2都与 进行比较len(grid),但您似乎没有方形网格,因此其中一项检查将不正确。大概应该改成:

if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]):
    if closed[x2][y2] == 0 and grid[x2][y2] == 0:
        g2 = g + cost

潜在的第三个问题是函数的意图似乎是search()返回一些东西,但它没有任何return声明。然后它会自动总是返回None,这意味着print search()底部的语句总是简单地打印None。从您的问题中不清楚您希望函数返回什么,所以我无法确定如何修复它。


观察这部分中的任何一个评论都令人困惑也可能很有用:

delta = [[-1, 0], # go up
         [ 0,-1], # go left
         [ 1, 0], # go down
         [ 0, 1]] # go right

或者使用变量名称(例如xy表示坐标)令人困惑。在技​​术意义上不是问题,但在此实现中,x坐标由带有“上”和“下”注释的条目修改,而y坐标由“左转”和“右转”修改。


推荐阅读