首页 > 解决方案 > 为什么在比较 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)

标签: rarraysn-queens

解决方案


推荐阅读