This is my first crack at the problem, I made an algorithm that can solve the tour for a board size nxn using back-tracing.
Code:
#!/usr/bin/env python
def find_tour(size, start_x, start_y):
moves = [[1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]]
board = []
trace = []
n_move = 1
for i in range(0, size):
board.append([-1] * size)
board[0][0] = 0
cur_x = start_x
cur_y = start_y
while n_move < size * size:
p = []
for move in moves:
move_x = cur_x + move[0]
move_y = cur_y + move[1]
if (move_x >= 0) and (move_y >= 0) and (move_x < size) and (move_y < size) and (board[move_x][move_y] == -1):
p.append((move_x, move_y))
while not len(p):
cur_x, cur_y, p = trace.pop()
board[cur_x][cur_y] = -1
n_move -= 1;
cur_x, cur_y = p.pop()
board[cur_x][cur_y] = n_move
trace.append((cur_x, cur_y, p))
n_move += 1
return board
b = find_tour(8, 0, 0)
print b
This is pretty slow but it works so far. I plan to create a GUI to better visualize the tour tomorrow.
Here is the output for 5x5:
Code:
jmccaffrey@windy:~/mywork/knights-tour$ time ./pytour.py
[[0, 3, 8, 17, 20], [9, 16, 19, 2, 7], [4, 1, 12, 21, 18], [15, 10, 23, 6, 13], [24, 5, 14, 11, 22]]
real 0m0.113s
user 0m0.112s
sys 0m0.000s
Bookmarks