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

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

我是 R 的新手,我正在尝试解决一个骑士访问棋盘中所有动作的最小步数。

我从以下位置获得了 python 代码: https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/

我试着把它翻译成 r。

但我总是出错,我不知道哪里出错了。

这是我的代码:

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

谢谢!

问题是 python 代码依赖 short-circuiting 来防止 out-of-bounds 错误。 & 不会 short-circuit 所以你需要使用 &&.

这是一个例子

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

FALSE & stop()
#> Error: 

valid_move更新为

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