Having watched the Computerphile video on backtracking, I've decided to attempt to implement this algorithm for a different problem. My code seems to work up until depth ~48 when it starts to endlessly iterate through depth 46-53. It is not a problem of memory, as for a 6x6 table it gets stuck similarly around depth 20.
table = np.zeros((8, 8)) - 1
table[0, 0] = 0
knightDOWN = [1, 2, 2, 1, -1, -2, -2, -1]
knightRIGHT = [2, 1, -1, -2, -2, -1, 1, 2]
depth = 0
def correctmove(move, startROW, startCOL):
newROW = startROW + knightDOWN[move]
newCOL = startCOL + knightRIGHT[move]
if newROW < 0 or newROW > 7:
return False
if newCOL < 0 or newCOL > 7:
return False
if table[newROW, newCOL] != -1:
return False
return True
def goBoard(startROW, startCOL, nummove):
if depth == 64:
print(table)
exit()
for x in range(0, 8):
if correctmove(x, startROW, startCOL):
print(table[startROW, startCOL])
startROW += knightDOWN[x]
startCOL += knightRIGHT[x]
table[startROW, startCOL] = nummove
nummove += 1
goBoard(startROW, startCOL, nummove)
table[startROW, startCOL] = -1
startROW -= knightDOWN[x]
startCOL -= knightRIGHT[x]
nummove -= 1
return
goBoard(0, 0, 0)
The code is basically supposed to check whether it can go with the knight to some new position, do it until it cannot move forward anymore and at this point the part of code after recursion call resets it back again. After seeing sample tables it seems to correctly create those first 50 or so tries but gets stuck on those and iterates over and over.