Skip to content

Commit aedc4ba

Browse files
committed
ref(chore): make code more readable
1 parent b728110 commit aedc4ba

File tree

1 file changed

+24
-16
lines changed

1 file changed

+24
-16
lines changed

backtracking/knight_tour.py

+24-16
Original file line numberDiff line numberDiff line change
@@ -26,35 +26,43 @@ def __init__(self, board_size: int):
2626
self.board_size = board_size
2727
self.board = [[0 for _ in range(board_size)] for _ in range(board_size)]
2828

29-
def get_valid_moves(self, position: tuple[int, int]) -> list[tuple[int, int]]:
29+
def _is_valid_move(self, position: tuple[int, int], move: tuple[int, int]) -> bool:
3030
"""
31-
Find all the valid positions a knight can move to from the current position.
32-
33-
>>> solver = KnightTourSolver(4)
34-
>>> solver.get_valid_moves((1, 3))
35-
[(2, 1), (0, 1), (3, 2)]
31+
Checks if a move is valid from the current position.
3632
"""
3733
y, x = position
34+
dy, dx = move
35+
new_y, new_x = y + dy, x + dx
36+
return 0 <= new_y < self.board_size and 0 <= new_x < self.board_size
37+
38+
def _get_valid_moves(self, position: tuple[int, int]) -> list[tuple[int, int]]:
39+
"""
40+
Find all the valid positions a knight can move to from the current position.
41+
"""
3842
return [
39-
(y + dy, x + dx)
43+
(position[0] + dy, position[1] + dx)
4044
for dy, dx in self.MOVES
41-
if 0 <= y + dy < self.board_size and 0 <= x + dx < self.board_size
45+
if self._is_valid_move(position, (dy, dx))
4246
]
4347

44-
def solve_knight_tour(self, position: tuple[int, int], move_number: int) -> bool:
48+
def _solve_knight_tour(self, position: tuple[int, int], move_number: int) -> bool:
4549
"""
4650
Helper function to solve the Knight's Tour problem recursively.
4751
"""
4852
if move_number == self.board_size * self.board_size + 1:
53+
# Base case: all cells visited
4954
return True
5055

51-
for next_position in self.get_valid_moves(position):
52-
ny, nx = next_position
53-
if self.board[ny][nx] == 0:
54-
self.board[ny][nx] = move_number
55-
if self.solve_knight_tour(next_position, move_number + 1):
56+
for next_position in self._get_valid_moves(position):
57+
# Move is valid and cell is not visited yet
58+
new_y, new_x = next_position
59+
if self.board[new_y][new_x] == 0:
60+
self.board[new_y][new_x] = move_number
61+
if self._solve_knight_tour(next_position, move_number + 1):
62+
# Recursive call for the next move
5663
return True
57-
self.board[ny][nx] = 0
64+
# Backtrack if no solution found
65+
self.board[new_y][new_x] = 0
5866

5967
return False
6068

@@ -75,7 +83,7 @@ def find_knight_tour(self) -> list[list[int]]:
7583
for i in range(self.board_size):
7684
for j in range(self.board_size):
7785
self.board[i][j] = 1
78-
if self.solve_knight_tour((i, j), 2):
86+
if self._solve_knight_tour((i, j), 2):
7987
return self.board
8088
self.board[i][j] = 0
8189
error_message = (

0 commit comments

Comments
 (0)