Created
May 25, 2018 13:28
-
-
Save PM2Ring/9234d8ea106bc6a4b4bc87338732d3c7 to your computer and use it in GitHub Desktop.
Knight tour, using recursive backtracking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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