棋盘格算法实现

时间:2013-07-23 08:57:06

标签: python dynamic-programming

def Checker(n):
    p = [[7,3,5,6,1],[2,6,7,0,2],[3,5,7,8,2],[7,6,1,1,4],[6,7,4,7,8]]  #profit of each cell
    cost = [[0 for j in range(n)] for i in range(n)]
    w = [[0 for j in range(n)] for i in range(n)]   #w[i, j] store the column number (j) of the previous square from which we moved to the current square at [i,j]
   for j in range(1,n):
       cost[1][j] = 0
   for i in range(2,n):
        for j in range(1,n):
            max = cost[i-1][j] + p[i-1][j]
            w[i][j] = j
            if (j > 1 and cost[i-1][j-1] + p[i-1][j-1] > max):
                max = cost[i-1][j-1] + p[i-1][j-1]
                w[i][j] = j-1
            if (j < n and cost[i-1][j+1] + p[i-1][j+1] > max):
                max = cost[i-1][j+1] + p[i-1][j+1]
                w[i][j] = j+1
            cost[i][j] = max
            print cost[i][j]
    maxd = cost[1][1]
    maxj = 1
    for j in range(2,n):
        if cost[1][j] >maxd:
            maxd = cost[1][j]
            maxj = j
    print "Maximum profit is: ",maxd
    printsquares(w,n,maxj)

def printsquares(w,i,j):
    if i == -1:
        return
    print "Square at row %d and column %d"%(i,j)
    printsquares(w,i-1,w[i][j])

if __name__ == '__main__':
    print "5*5 checker board problem"
    n = 5
    Checker(n)

上面的程序是在python中实现棋盘格算法。 当我运行上面的代码时,会显示以下错误:

  

if(j&lt; n and cost [i-1] [j + 1] + p [i-1] [j + 1]&gt; max):IndexError:list   指数超出范围

我做错了什么,有人会为它提出解决方案吗?

3 个答案:

答案 0 :(得分:0)

你几乎想要这样做:

L = range(5)
print L[5+1]

cost[i-1][j+1]

没有第6个元素。只有五个。因此IndexError

至于解决方案,如果你想要最后一个元素,你可能只想要n而不是n+1。但是,我不是百分百肯定。

答案 1 :(得分:0)

看起来您正在尝试从列表从1开始的语言调整算法,而在Python中从0开始。就检查而言,您永远不会访问cost[i][0]

答案 2 :(得分:0)

要避免IndexError异常,

if (j < n and cost[i-1][j+1] + p[i-1][j+1] > max):
  max = cost[i-1][j+1] + p[i-1][j+1]

应写成:

if (j < n-1 and cost[i-1][j+1] + p[i-1][j+1] > max):
  max = cost[i-1][j+1] + p[i-1][j+1]

printsquares(w,i-1,w[i][j])

变为

printsquares(w,i-1,w[i-1][j])

但正如其他研究员所说,我不确定该算法是否正确实施。

相关问题