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
JavaScript
x
34
34
1
visited = [[False for x in range(5)] for y in range(5)]
2
3
def move(x,y,m):
4
5
result=False
6
if x<0 or x>=5 or y<0 or y>=5:
7
return False
8
if visited[x][y]==True:
9
return False
10
if m==24:
11
print "a solution has been found"
12
print x,",",y
13
14
15
visited[x][y]=True
16
return True
17
18
else:
19
result=result or move(x+2,y+1,m+1)
20
result=result or move(x+2,y-1,m+1)
21
result=result or move(x-2,y+1,m+1)
22
result=result or move(x-2,y-1,m+1)
23
result=result or move(x+1,y+1,m+1)
24
result=result or move(x+1,y-1,m+1)
25
result=result or move(x-1,y+1,m+1)
26
result=result or move(x-1,y-1,m+1)
27
if result==True:
28
print x,",",y
29
30
return True
31
else:
32
visited[x][y]=False
33
return False
34
Advertisement
Answer
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:
JavaScript
1
26
26
1
N = 5 # This way you can test it with 5 or 6 and even 100 if you want to.
2
visited = [[False for x in range(N)] for y in range(N)]
3
4
def move(x,y,m):
5
6
result=False
7
if x<0 or x>=N or y<0 or y>=N or visited[x][y]==True: # You may merge these two ifs.
8
return False
9
visited[x][y]=True
10
if m==(N * N - 1):
11
print "a solution has been found"
12
visited[x][y]=True # Set visited here tot true.
13
return True
14
else:
15
print x,",",y
16
if (move(x+2,y+1,m+1) or move(x+2,y-1,m+1)
17
or move(x-2,y+1,m+1) or move(x-2,y-1,m+1)
18
or move(x+1,y+1,m+1) or move(x+1,y-1,m+1)
19
or move(x-1,y+1,m+1) or move(x-1,y-1,m+1)): # Place them in one if.
20
print x,",",y
21
22
return True
23
return False # If the algorithm comes here it may return false
24
25
print move(2,1,0)
26