在javascript中执行Nqueens

时间:2017-03-08 06:12:13

标签: javascript

我尝试使用javascript实现 N-Queens问题并使用节点 REPL js解释器执行它。 以下是我使用过的两个主要功能:

 function isSafe( board, row, column){

 //To check for a queen in the same row to the left
 for (i=0;i<column;i++)
  if(board[row][i])
   return false;
 //To check for a queen diagonally below to the left
 for ( i=0 , j=0 ; i<row , j< column; i++ , j++)
  if (board[i][j])
   return false;
 //To check for a queen diagonally above to the left.
 for (i=board[0].length-1 , j=0 ; i> row ,  j<column; i-- ,j++)
  if (board[i][j])
   return false;
 //Otherwise the queen can be placed
  return true;
}

和      函数NQUtil(board,column){

 if(column==board[0].length-1)
 {
    for(i=0;i<board.length ; i++)
        console.log(board[i]);
    return true;
 }
for ( i =0 ; i< board[0].length;i++){
if(isSafe(board,i,column))  
    board[i][column]=1;
NQUtil(board, column+1);    
board[i][column]=0;
return false;
 }
}

这是我将板矩阵(板,0)传递给NQUtil函数时的错误:

board[i][column]=0;
            ^

TypeError: Cannot set property '2' of undefined

当我将(数组(板),列)传递给每个递归调用NQUtil以克服未定义的&#39;问题我明白了:

function isSafe( board, row, column){
           ^

RangeError: Maximum call stack size exceeded
at isSafe (/home/vivek/nqueens.js:2:16)
at NQUtil (/home/vivek/nqueens.js:30:5)
at NQUtil (/home/vivek/nqueens.js:32:2)
at NQUtil (/home/vivek/nqueens.js:32:2)
at NQUtil (/home/vivek/nqueens.js:32:2)
at NQUtil (/home/vivek/nqueens.js:32:2)
at NQUtil (/home/vivek/nqueens.js:32:2)
at NQUtil (/home/vivek/nqueens.js:32:2)
at NQUtil (/home/vivek/nqueens.js:32:2)
at NQUtil (/home/vivek/nqueens.js:32:2)

传递一个4x4的零数组 - 一个未占用的棋盘,我无法找出调用堆栈到底溢出的位置。请帮我。 谢谢, Vivek Vasudevan。

更新:这是我创建零数组的功能:

 function zeros(dimensions) {
 var array = new Array(dimensions[0]);
 for(var i =0; i<dimensions[0]; i++)
  array[i]=new Array(dimensions[1]);
 for(var i=0;i<dimensions[0];i++)
  for(var j=0;j<dimensions[1];j++)
   array[i][j]=0    
 return array;
 }

这些是对函数的调用:

 board=zeros([4,4]);

 NQUtil(board , 0);

0 个答案:

没有答案