Search code examples
rknights-tour

Error: subscript out of bounds (knight's tour)


im new to R and im trying to solve for the minimum number of moves for a knight visit all the moves in a chess board.

I got the python code from: https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/

and i tried to translate it to r.

But i am always getting the error and I don't know where I went wrong.

This is my 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
        }
    }
}

main <- function() {
    sims = 10
    ctr = 0
    number_of_moves = c()

    solve(board, 1, 1, move_x, move_y, pos)

    print(paste("Minimum number of moves: ", pos))
}


main()

Thanks!


Solution

  • The problem is that the python code relies on short-circuiting to prevent out-of-bounds errors. & will not short-circuit so you need to use &&.

    Here is an example

    FALSE && stop()
    #> [1] FALSE
    
    FALSE & stop()
    #> Error: 
    

    Update valid_move to this

    valid_move <- function (x, y, board) {
        # Changed to && to allow short-circuiting
        # if (x >= 1 & y >= 1 & x <= 8 & y <= 8 & board[x, y] == -1) {
        if (x >= 1 && y >= 1 && x <= 8 && y <= 8 && board[x, y] == -1) {
            return (T)
        }
        return (F)
    }