【问题标题】:Error: subscript out of bounds (knight's tour)错误:下标越界(骑士之旅)
【发布时间】:2021-01-30 20:51:58
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: r knights-tour


    【解决方案1】:

    问题在于 python 代码依赖于短路来防止越界错误。 &amp;不会短路,所以需要使用&amp;&amp;

    这是一个例子

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 2016-05-27
      • 1970-01-01
      相关资源
      最近更新 更多