I am working on knight's tour problem, and using backtracking algorithm. My code doesn't produce the right output in the end it just repeats the last two entries over and over until n^2 -1 is not reached.
This is my code. I am following this pseudocode http://www.wou.edu/~broegb/Cs345/KnightTour.pdf
visited = [[False for x in range(5)] for y in range(5)]
def move(x,y,m):
result=False
if x<0 or x>=5 or y<0 or y>=5:
return False
if visited[x][y]==True:
return False
if m==24:
print "a solution has been found"
print x,",",y
visited[x][y]=True
return True
else:
result=result or move(x+2,y+1,m+1)
result=result or move(x+2,y-1,m+1)
result=result or move(x-2,y+1,m+1)
result=result or move(x-2,y-1,m+1)
result=result or move(x+1,y+1,m+1)
result=result or move(x+1,y-1,m+1)
result=result or move(x-1,y+1,m+1)
result=result or move(x-1,y-1,m+1)
if result==True:
print x,",",y
return True
else:
visited[x][y]=False
return False
You are settings
visited[x][y]=True
to true at the end of your algorithm. It has to be set after you check you've bin there. I also made a couple of enhancements for your code: