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

Function open_knight_tour

backtracking/knight_tour.py:71–95  ·  view source on GitHub ↗

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

(n: int)

Source from the content-addressed store, hash-verified

69
70
71def open_knight_tour(n: int) -> list[list[int]]:
72 """
73 Find the solution for the knight tour problem for a board of size n. Raises
74 ValueError if the tour cannot be performed for the given size.
75
76 >>> open_knight_tour(1)
77 [[1]]
78
79 >>> open_knight_tour(2)
80 Traceback (most recent call last):
81 ...
82 ValueError: Open Knight Tour cannot be performed on a board of size 2
83 """
84
85 board = [[0 for i in range(n)] for j in range(n)]
86
87 for i in range(n):
88 for j in range(n):
89 board[i][j] = 1
90 if open_knight_tour_helper(board, (i, j), 1):
91 return board
92 board[i][j] = 0
93
94 msg = f"Open Knight Tour cannot be performed on a board of size {n}"
95 raise ValueError(msg)
96
97
98if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

open_knight_tour_helperFunction · 0.85

Tested by

no test coverage detected