Lesson goal: The Eight Queens Puzzle & Combinatorics

Previous: Chessboard coordinates and moving pieces | Home | Next: The Knight's Tour and vector geometry

In 1848, chess composer Max Bezzel posed one of the most famous problems in all of mathematics: The Eight Queens Puzzle.

The challenge: Place 8 queens on an $8 \times 8$ chessboard such that no two queens attack each other!

Since a queen in chess can move horizontally, vertically, and diagonally across any number of squares, this means:
  1. Rows and Columns: No two queens can share the same file ($x_1 \neq x_2$) or the same rank ($y_1 \neq y_2$).
  2. Diagonals: Two squares $(x_1, y_1)$ and $(x_2, y_2)$ lie on the same diagonal if and only if: $$|x_1 - x_2| = |y_1 - y_2|$$ Therefore, for every pair of queens, $|x_1 - x_2| \neq |y_1 - y_2|$.
The legendary mathematician Carl Friedrich Gauss studied this problem extensively. Out of the $4,426,165,368$ possible ways to place 8 pieces on 64 squares, there are exactly 92 distinct solutions (or 12 unique solutions up to rotations and reflections)!

With chess_board("empty") and chess_put("wQ", x, y), we can place queens onto the board directly using Lua loops and coordinates.
chess_board("empty")
chess_put("wQ", "a4")

chess_put("wQ", "b7")

chess_put("wQ", "c3")
Move the mouse over a dotted box for more information.

  • Piece Codes: "wQ" (White Queen), "wK" (White King), "wR" (Rook), "wB" (Bishop), "wN" (Knight), "wP" (Pawn). Prefix with b for Black pieces.
  • Verification: Look down every row, column, and diagonal on the board — none of the 8 queens share a line of sight!

Now you try. Another famous solution has the queen ranks as: {5, 2, 6, 1, 7, 4, 8, 3}. Change the queens_ranks array to this new solution and run the code!

Type your code here:


See your results here: