countNQueensSolutions

PHOTO EMBED

Thu Jun 24 2021 05:27:15 GMT+0000 (Coordinated Universal Time)

Saved by @ejiwen #javascript

window.countNQueensSolutions = function(n) {
  var solutionCount = 0; //fixme


    // means we reached the end of the board.
    // but what if reached the end of the board, but don't have a solution? will that never happen?
  var board = new Board({'n': n});

  // recurse on columns
  var repeat = function(board,j){

    // means we reached the end of the board.
    // but what if reached the end of the board, but don't have a solution? will that never happen?

    if(j >= n){
      return true;
    }



   for(var i = 0; i < n; i++) // loop on rows
   {
      board.togglePiece(i, j);
     if(!board.hasRowConflictAt(i) && !board.hasMajorDiagonalConflictAt(board._getFirstRowColumnIndexForMajorDiagonalOn(i,j))
      && !board.hasMinorDiagonalConflictAt(board._getFirstRowColumnIndexForMinorDiagonalOn(i,j)))
     {
       if(repeat(board, j + 1) === true)
       {
        solutionCount++;
       }

     }
     board.togglePiece(i, j);
   };



    return false;
  }

  repeat(board,0);

  console.log('Number of solutions for ' + n + ' queens:', solutionCount);
  return solutionCount;
};
content_copyCOPY