Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ref: refactor KnightTour implementation #11356

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
161 changes: 75 additions & 86 deletions backtracking/knight_tour.py
Original file line number Diff line number Diff line change
@@ -1,98 +1,87 @@
# Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM

from __future__ import annotations


def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]:
"""
Find all the valid positions a knight can move to from the current position.

>>> get_valid_pos((1, 3), 4)
[(2, 1), (0, 1), (3, 2)]
"""

y, x = position
positions = [
(y + 1, x + 2),
(y - 1, x + 2),
(y + 1, x - 2),
(y - 1, x - 2),
(y + 2, x + 1),
(y + 2, x - 1),
(y - 2, x + 1),
(y - 2, x - 1),
]
permissible_positions = []

for position in positions:
y_test, x_test = position
if 0 <= y_test < n and 0 <= x_test < n:
permissible_positions.append(position)

return permissible_positions


def is_complete(board: list[list[int]]) -> bool:
"""
Check if the board (matrix) has been completely filled with non-zero values.

>>> is_complete([[1]])
True

>>> is_complete([[1, 2], [3, 0]])
False
"""

return not any(elem == 0 for row in board for elem in row)
from typing import ClassVar


def open_knight_tour_helper(
board: list[list[int]], pos: tuple[int, int], curr: int
) -> bool:
class KnightTourSolver:
"""
Helper function to solve knight tour problem.
Represents a solver for the Knight's Tour problem.
"""

if is_complete(board):
return True
MOVES: ClassVar[list[tuple[int, int]]] = [
(1, 2),
(-1, 2),
(1, -2),
(-1, -2),
(2, 1),
(-2, 1),
(2, -1),
(-2, -1),
]

for position in get_valid_pos(pos, len(board)):
def __init__(self, board_size: int):
"""
Initializes the KnightTourSolver with the specified board size.
"""
self.board_size = board_size
self.board = [[0 for _ in range(board_size)] for _ in range(board_size)]

def get_valid_moves(self, position: tuple[int, int]) -> list[tuple[int, int]]:
"""
Find all the valid positions a knight can move to from the current position.

>>> solver = KnightTourSolver(4)
>>> solver.get_valid_moves((1, 3))
[(2, 1), (0, 1), (3, 2)]
"""
y, x = position

if board[y][x] == 0:
board[y][x] = curr + 1
if open_knight_tour_helper(board, position, curr + 1):
return True
board[y][x] = 0

return False


def open_knight_tour(n: int) -> list[list[int]]:
"""
Find the solution for the knight tour problem for a board of size n. Raises
ValueError if the tour cannot be performed for the given size.

>>> open_knight_tour(1)
[[1]]

>>> open_knight_tour(2)
Traceback (most recent call last):
...
ValueError: Open Knight Tour cannot be performed on a board of size 2
"""

board = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
for j in range(n):
board[i][j] = 1
if open_knight_tour_helper(board, (i, j), 1):
return board
board[i][j] = 0

msg = f"Open Knight Tour cannot be performed on a board of size {n}"
raise ValueError(msg)
return [
(y + dy, x + dx)
for dy, dx in self.MOVES
if 0 <= y + dy < self.board_size and 0 <= x + dx < self.board_size
]

def solve_knight_tour(self, position: tuple[int, int], move_number: int) -> bool:
"""
Helper function to solve the Knight's Tour problem recursively.
"""
if move_number == self.board_size * self.board_size + 1:
return True

for next_position in self.get_valid_moves(position):
ny, nx = next_position
if self.board[ny][nx] == 0:
self.board[ny][nx] = move_number
if self.solve_knight_tour(next_position, move_number + 1):
return True
self.board[ny][nx] = 0

return False

def find_knight_tour(self) -> list[list[int]]:
"""
Find a solution for the Knight's Tour problem for the initialized board size.
Raises ValueError if the tour cannot be performed for the given size.

>>> solver = KnightTourSolver(1)
>>> solver.find_knight_tour()
[[1]]
>>> solver = KnightTourSolver(2)
>>> solver.find_knight_tour()
Traceback (most recent call last):
...
ValueError: Knight's tour cannot be performed on a board of size 2
"""
for i in range(self.board_size):
for j in range(self.board_size):
self.board[i][j] = 1
if self.solve_knight_tour((i, j), 2):
return self.board
self.board[i][j] = 0
error_message = (
f"Knight's tour cannot be performed on a board of size {self.board_size}"
)
raise ValueError(error_message)


if __name__ == "__main__":
Expand Down