countNRooksSolutions

PHOTO EMBED

Thu Jun 24 2021 05:26:12 GMT+0000 (Coordinated Universal Time)

Saved by @ejiwen #javascript

 var solutionCount = 0; //fixme
  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);

      // we only check for row conflict, since we never place two items(rooks/queens) in the same column,
      // when we place a piece, we go to the next column straight away.
     if(!board.hasRowConflictAt(i))
     {
       if(repeat(board, j + 1) === true)
       {

        solutionCount++;
        //return true;
       }

     }
     board.togglePiece(i, j);
   }



    return false;
  }

  repeat(board,0);
content_copyCOPY