I'm new to R and I'm trying to find the least number of moves it takes for the knight to move around a chess board when it starts from the corner.
I used the Python algorithm from this website: https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/
and I tried to translate it to R.
However, when I run the program, its output is:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 0 -1 -1 -1 -1 -1 -1 -1
[2,] -1 -1 -1 -1 -1 -1 -1 -1
[3,] -1 -1 -1 -1 -1 -1 -1 -1
[4,] -1 -1 -1 -1 -1 -1 -1 -1
[5,] -1 -1 -1 -1 -1 -1 -1 -1
[6,] -1 -1 -1 -1 -1 -1 -1 -1
[7,] -1 -1 -1 -1 -1 -1 -1 -1
[8,] -1 -1 -1 -1 -1 -1 -1 -1
[1] "Minimum number of moves: -1"
What can I do to fix this issue?
This is the code:
chess = rep(-1, times = 64)
board = matrix(data = chess, nrow = 8, ncol = 8, byrow = TRUE)
move_x = c(2, 1, -1, -2, -2, -1, 1, 2)
move_y = c(1, 2, 2, 1, -1, -2, -2, -1)
board[1, 1] = 0
pos = 1
valid_move <- function (x, y, board) {
if (x >= 1 && y >= 1 && x <= 8 && y <= 8 && board[x, y] == -1) {
return (T)
}
return (F)
}
solve <- function (board, curr_x, curr_y, move_x, move_y, pos) {
if (pos == 64) {
return (T)
}
for (i in seq(1, 8)) {
new_x = curr_x + move_x[i]
new_y = curr_y + move_y[i]
if (valid_move(new_x, new_y, board)) {
board[new_x, new_y] = pos
if (solve(board, new_x, new_y, move_x, move_y, (pos+1))) {
return (TRUE)
}
board[new_x, new_y] = -1
}
}
return (F)
}
main <- function() {
sims = 10
ctr = 0
number_of_moves = c()
solve(board, 1, 1, move_x, move_y, pos)
for (x in board) {
for (y in board) {
number_of_moves <- c(number_of_moves, board[x, y])
}
}
print(board)
print(paste("Minimum number of moves: ", min(number_of_moves)))
}
main()