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; };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter