【发布时间】:2021-09-07 08:53:09
【问题描述】:
我对我为以下问题编写的回溯解决方案有疑问:
Given a square chessboard of N x N size, the position of Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position
我的回溯解决方案是:
#knight walk problem
#knight walk problem
#cx---crnt x value
#cy---crnt y value
#Dx---destintion X value
#Dy----destintion Y value
#count---count of steps
def kingnight(Cx,Cy,Dx,Dy,outboard,steps):
if Cx==Dx and Cy==Dy:
outboard[Cx][Cy]=1
return steps
if Cx<0 or Cy<0 or Cx>=len(outboard) or Cy>=len(outboard) or outboard[Cx][Cy]==1:
return float('inf')
outboard[Cx][Cy]=1
min1=kingnight(Cx+2,Cy-1,Dx,Dy,outboard,steps+1)
min2=kingnight(Cx+2,Cy+1,Dx,Dy,outboard,steps+1)
min3=kingnight(Cx-2,Cy+1,Dx,Dy,outboard,steps+1)
min4=kingnight(Cx-2,Cy-1,Dx,Dy,outboard,steps+1)
min5=kingnight(Cx+1,Cy+2,Dx,Dy,outboard,steps+1)
min6=kingnight(Cx+1,Cy-2,Dx,Dy,outboard,steps+1)
min7=kingnight(Cx-1,Cy+2,Dx,Dy,outboard,steps+1)
min8=kingnight(Cx-1,Cy-2,Dx,Dy,outboard,steps+1)
crntmin=min(min1,min2,min3,min4,min5,min6,min7,min8)
outboard[Cx][Cy]=0 #backtracking
return crntmin
当我调用函数时:
n=4
board=[[0 for _ in range(n)] for i in range(n)]
kingnight(1,1,0,0,board,0)
它显示了预期的输出。但是当我用以下方式打电话时:
n=6
board=[[0 for _ in range(n)] for i in range(n)]
kingnight(2,3,5,5,board,0)
它应该返回 3,但它是一个无限循环。
我哪里错了?
【问题讨论】:
标签: python algorithm recursion backtracking recursive-backtracking