Skip to main content

Knight's Tour

Definition​

The Knight's Tour Algorithm is a method used to solve the puzzle of moving a knight chess piece to visit every square on a chessboard exactly once

Practice​

knight_tour(board, row, col, move_count):
if move_count == board.size ** 2:
return true // All squares visited, tour complete

for each possible move from (row, col) as (next_row, next_col):
if is_valid_move(board, next_row, next_col):
mark_square_as_visited(board, next_row, next_col, move_count)
if knight_tour(board, next_row, next_col, move_count + 1):
return true // Successful tour found
else:
unmark_square(board, next_row, next_col) // Backtrack
return false // No successful tour found

initialize chessboard
start_row, start_col = choose_starting_position(chessboard)
if knight_tour(chessboard, start_row, start_col, 1):
print("Successful tour found")
else:
print("No tour found")