I’m trying to solve the knight tour algorithms with recursive backtracking method in python.
The solution should be a matrix with 24 documented steps, but it only count up-to 5 steps. It doesn’t enter the recursive if statement.
JavaScript
x
33
33
1
JUMP_POS = [ (2,1),
2
(2,-1),
3
(1,2),
4
(1,-2),
5
(-1,2),
6
(-1,-2),
7
(-2,1),
8
(-2,-1)
9
]
10
11
def springen(x, y, nr, matrix):
12
matrix_len = len(matrix)
13
matrix[x][y] = nr
14
if nr == ( (matrix_len*matrix_len) -1 ):
15
print("good", matrix)
16
return True
17
else:
18
for pos in JUMP_POS:
19
xNeu = x + pos[0]
20
yNeu = x + pos[1]
21
22
if xNeu >= 0 and xNeu < matrix_len and yNeu >= 0 and yNeu < matrix_len:
23
if matrix[xNeu][yNeu] == 0: #check, if position is empty
24
if springen(xNeu, yNeu, nr+1, matrix):
25
#this section is not passing
26
return True
27
28
matrix[x][y] = 0
29
return False
30
31
matrix = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
32
print(springen(0,0,0,matrix))
33
Advertisement
Answer
The problem I see is that you set yNeu = x + pos[1]
when you probably meant yNeu = y + pos[1]
.
Another potential problem is that since you use 0
both for the first step and to mark unvisited squares, you can revisit the starting square later, so consider using -1
or None
to mark unvisited locations.