我编写并运行了一个AI搜索程序,从起点开始搜索直到找到终点或结果。然而,当我运行它时,我没有得到搜索结果,反而得到了“fail”和“none”。任何关于可能导致此问题的原因的建议将不胜感激。
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 = 1delta = [[-1, 0], # go up [ 0,-1], # go left [ 1, 0], # go down [ 0, 1]] # go rightdelta_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] = 1print search()
回答:
第一个问题出现在代码的这一部分:
x = next[3]y = next[4]g = next[1]
open
列表中的每个元素只有三个条目,因此3
和4
是无效的索引。这应该改为:
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
x2
和y2
都与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
或者使用x
和y
这样的变量名来表示坐标可能会引起混淆。从技术上讲这不是问题,但在这种实现中,x
坐标会被带有“向上”和“向下”注释的条目修改,而y
坐标会被“向左”和“向右”修改。