Knight walk 回溯解决方案问题

问题描述

我对我为以下问题编写的回溯解决方案有疑问:

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,steps+1)
  min2=kingnight(Cx+2,Cy+1,steps+1)
  min3=kingnight(Cx-2,steps+1)
  min4=kingnight(Cx-2,steps+1)
  min5=kingnight(Cx+1,Cy+2,steps+1)
  min6=kingnight(Cx+1,Cy-2,steps+1)
  min7=kingnight(Cx-1,steps+1)
  min8=kingnight(Cx-1,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,board,0)

它显示了预期的输出。但是当我打电话给以下内容时:

n=6
board=[[0 for _ in range(n)] for i in range(n)]
kingnight(2,3,5,0)

它应该返回 3 但这是一个无限循环。

我错在哪里?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)