My knight's tour code taking a long time to generate the output but it seems to be working fine until it reaches 61st step. What problem is making this code slower and inefficient? This code is working fine for 5*5,6*6 but it's getting slower when I try this code with 7*7 or beyond. What improvements need to be done to make it as quick as possible without waiting a long time for 8*8
output?
def isSafe(x,y,array):
return x>=0 and x<8 and y>=0 and y<8 and array[x][y]==-1
def knightsTour(x,y,moveI,x_move,y_move,solution):
if moveI==65:
return True
#try out all different configuration
for k in range(8):
x_value= x + x_move[k]
y_value = y + y_move[k]
for x1 in range(8):
print(solution[x1])
print()
if isSafe(x_value,y_value,solution):
solution[x_value][y_value] = moveI
if knightsTour(x_value,y_value,moveI+1,x_move,y_move,solution) is True:
return True
else:
solution[x_value][y_value]=-1
return False
x_move=[ 2, 1, -1, -2, -2, -1, 1, 2 ]
y_move=[1, 2, 2, 1, -1, -2, -2, -1]
solution = [[-1 for x in range(8)] for x in range(8)]
solution[0][0]=1
knightsTour(0,0,2,x_move,y_move,solution)