python编程计算棋盘放米_棋盘算法实现

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 < n and cost[i-1][j+1] + p[i-1][j+1] > max): IndexError: list

index out of range

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值