N-Queens As A Search Problem
On a chessboard, a queen is dangerous because one placement rules out many squares. Turning that into a search problem starts by describing exactly which squares a queen attacks so we can treat attacks as constraints that invalidate candidate placements. That shift matters because a solver can build a candidate solution step by step and reject partial candidates as soon as they break a rule, instead of waiting until the board is full.
Attacks become constraints
A placement is valid only if no two queens attack each other, which means three constraints must hold at the same time. Two queens cannot share a row, they cannot share a column, and they cannot share a diagonal.
To make those constraints concrete, inspect how a single queen at a specific coordinate marks attacked squares on a small board.
The row and column constraints are direct because every square with the same row index or the same column index is attacked. The diagonal constraint is still mechanical because squares stay on a diagonal when their row and column change together, so a queen attacks squares that lie along the two diagonal directions until the board edge stops the line.
A compact board representation
Once the constraints are clear, the next step is choosing a representation that makes it easy to build candidates incrementally. A simple choice is a one dimensional array where queens[row] = col, meaning the queen in row is placed in column col. With this representation, the row constraint is enforced by construction because each row index appears once.
The widget shows how a specific array corresponds to a drawn board position.
Sign up for free
Generate custom courses on any topic — with hands-on practice, AI guidance, and visuals built in.
Already have an account?