@@ -26,35 +26,43 @@ def __init__(self, board_size: int):
26
26
self .board_size = board_size
27
27
self .board = [[0 for _ in range (board_size )] for _ in range (board_size )]
28
28
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 :
30
30
"""
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.
36
32
"""
37
33
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
+ """
38
42
return [
39
- (y + dy , x + dx )
43
+ (position [ 0 ] + dy , position [ 1 ] + dx )
40
44
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 ))
42
46
]
43
47
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 :
45
49
"""
46
50
Helper function to solve the Knight's Tour problem recursively.
47
51
"""
48
52
if move_number == self .board_size * self .board_size + 1 :
53
+ # Base case: all cells visited
49
54
return True
50
55
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
56
63
return True
57
- self .board [ny ][nx ] = 0
64
+ # Backtrack if no solution found
65
+ self .board [new_y ][new_x ] = 0
58
66
59
67
return False
60
68
@@ -75,7 +83,7 @@ def find_knight_tour(self) -> list[list[int]]:
75
83
for i in range (self .board_size ):
76
84
for j in range (self .board_size ):
77
85
self .board [i ][j ] = 1
78
- if self .solve_knight_tour ((i , j ), 2 ):
86
+ if self ._solve_knight_tour ((i , j ), 2 ):
79
87
return self .board
80
88
self .board [i ][j ] = 0
81
89
error_message = (
0 commit comments