r - 为什么在比较 8 个皇后问题的 if 语句中的数组元素时出现“参数长度为 0”错误
问题描述
编辑:我遇到了一些索引问题和一些语法错误,我相应地更新了我的代码,但我仍然遇到同样的错误
我正在尝试使用 R 解决 8 个皇后问题,但是当我运行我的 checkOpen 函数时,它返回错误“参数长度为 0”。我很好奇为什么会发生这个错误,任何关于如何解决这个问题的建议将不胜感激!
checkOpen <- function(board, row, col){
for(i in col){
if(board[row,i,]== 1){
return(FALSE)
}
}
i <- row
j <- col
while(i > 0 && j > 0){
if (board[i,j,] == 1){
return(FALSE)
}
i <- i-1
j <- j-1
}
i <- row
j <- col
while(i < row && j > 0){
if(board[i,j,] == 1){
return(FALSE)
}
}
return(TRUE)
}
placeQueenRecursive <- function(board, column){
if(column >= col_global){
return(TRUE)
}
for(i in row_global){
if(checkOpen(board, i, column)){
board[i,column,] <- 1
if(placeQueenRecursive(board, column+1) == True){
return(TRUE)}
board[i,column,] <- 0}
}
}
placeQueen <- function(board,queens){
if(placeQueenRecursive(board, 0) == False){
print("No Solution")
return(FALSE)
}
print(board)
return(TRUE)
}
queens <<- 0
row_global <<- c(1,2,3,4,5,6,7,8)
col_global <<- c(1,2,3,4,5,6,7,8)
empty <- c(0,0,0,0,0,0,0,0)
board <<- array(c(empty, empty, empty, empty, empty, empty, empty, empty), dim = c(8,8,2))
print(board[1,1,])
print(board)
placeQueen(board,queens)
解决方案
推荐阅读
- shiny - 图像不会出现在 Shiny App 的 www 文件夹中
- docker - 如何在 dockerfile 中传递运行时参数?
- python - 使用 HTMLParser 获取带引号的属性
- javascript - HTML 表单输出格式(使用 JavaScript)
- database - spring boot 不同的微服务实例和数据完整性
- wpf - 在 Shell.xaml 中创建区域期间出现 KeyNotFoundException
- qt - 如何在 Qt Widgets 应用程序中使用阻塞的 UI 线程运行动画?
- css - 如何将背景图像的中心点向下移动?
- javascript - 如何将模型中的数据获取到 JavaScript 函数中?
- python - 使用 R 和 Python 的不同多项式回归系数