错误:下标超出范围骑士之旅

问题描述

我是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)
move_y = c(1,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,pos+1)) {
                return (TRUE)
            }
        board[new_x,new_y] = -1
        }
    }
}

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

    solve(board,pos)

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


main()

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)