MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / get_valid_pos

Function get_valid_pos

backtracking/knight_tour.py:6–32  ·  view source on GitHub ↗

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)]

(position: tuple[int, int], n: int)

Source from the content-addressed store, hash-verified

4
5
6def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]:
7 """
8 Find all the valid positions a knight can move to from the current position.
9
10 >>> get_valid_pos((1, 3), 4)
11 [(2, 1), (0, 1), (3, 2)]
12 """
13
14 y, x = position
15 positions = [
16 (y + 1, x + 2),
17 (y - 1, x + 2),
18 (y + 1, x - 2),
19 (y - 1, x - 2),
20 (y + 2, x + 1),
21 (y + 2, x - 1),
22 (y - 2, x + 1),
23 (y - 2, x - 1),
24 ]
25 permissible_positions = []
26
27 for inner_position in positions:
28 y_test, x_test = inner_position
29 if 0 <= y_test < n and 0 <= x_test < n:
30 permissible_positions.append(inner_position)
31
32 return permissible_positions
33
34
35def is_complete(board: list[list[int]]) -> bool:

Callers 1

open_knight_tour_helperFunction · 0.85

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected