Skip to content

Instantly share code, notes, and snippets.

@PM2Ring
Created May 25, 2018 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PM2Ring/9234d8ea106bc6a4b4bc87338732d3c7 to your computer and use it in GitHub Desktop.
Save PM2Ring/9234d8ea106bc6a4b4bc87338732d3c7 to your computer and use it in GitHub Desktop.
Knight tour, using recursive backtracking
#!/usr/bin/env python3
''' Knight tour, using recursive backtracking
Written by PM 2Ring 2018.05.25
'''
moves = ((-2, -1), (-2, 1), (-1, -2), (-1, 2),
(1, -2), (1, 2), (2, -1), (2, 1))
def knight(cy, cx, n=1):
if not(0 <= cy < size and 0 <= cx < size and not board[cy][cx]):
return False
board[cy][cx] = n
if n == hinum:
print('\n'.join([' '.join([f'{u:>2}' for u in row])
for row in board]), end='\n\n')
else:
for mx, my in moves:
y, x = cy + my, cx + mx
if knight(y, x, n + 1):
board[y][x] = 0
return True
size = 5
hinum = size * size
board = [[0] * size for _ in range(size)]
knight(0, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment