The 8 Queens Puzzle
18 Dec 2020

The eight queens puzzle is based on the classic stategy games problem which is in this case putting eight chess queens on an 8 × 8 chessboard such that none of them is able to capture any other using the standard chess queen's moves. Thus, a solution requires that no two queens share the same row, column, or diagonal.

The canvas above shows 8 different solutions for the 8 queens problem. The solutions are found using the backtracking recursive algorithm. The pseudo-code for which looks like this.

placeQueens(chessBoard, column) {
  //If all queens are placed then return true.
  //N is the size of the board.
  if (column >= N)
    return true;

  //Try placing this queen in all rows one by one
  for i in 0 to N {
    //Check if queen can be placed on chessBoard[i][col]
    if ( canPlace(chessBoard, i, column) ) {
      //Place this queen in chessBoard[i][col]
      //1 represents the queen being placed. 0 is empty.
      chessBoard[i][column] = 1;

      //recursively place rest of the queens
      if (placeQueens(chessBoard, column + 1))
        return true;

      //If placing queen in chessBoard[i][column]
      //doesn't lead to a solution, then remove that queen
      chessBoard[i][column] = 0; //BACKTRACK
    }
  }
  //If queen cannot be place in any row in this column
  //then return false
  return false;
}

You can place queens yourself and see if you can come with a different solution.
to reset the board.

1. 8queenscommon.js - Download, index.html
//Code goes here
2. 8queens.js - Download, index.html
//Code goes here
3. 8queensplay.js - Download, index.html
//Code goes here

Javascript Demos

Here's a bunch of javascript... things I wrote over the years whenever time permitted.