AI搜索程序不输出搜索矩阵

时间:2018-05-26 18:49:47

标签: python search artificial-intelligence

编写并运行了一个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()
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

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

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坐标由“向左”修改“和”走吧“。