Watch backtracking place queens row by row and undo a move when two queens attack each other. Worked example on the 4 by 4 board, then try boards up to 8 by 8.
About this algorithm
N-Queens asks you to place N chess queens on an N by N board so that no two attack each other: no shared row, column or diagonal. The backtracking solution places one queen per row, top to bottom, and the moment a row has no safe square left it goes back and moves the queen in the row above.
N-Queens is the cleanest picture of backtracking with a safety check, which is why it is the standard textbook and interview example. Among its neighbours here, Sudoku is the same idea on a fixed board with three kinds of clash (row, column and box), so its runs are far longer; Rat in a Maze backtracks over a path instead of a set of placements; and Tower of Hanoi never backtracks at all. To count every arrangement for a large N, track the used columns and both diagonal directions in sets or bit masks so each safety check costs O(1).
Two queens in one row always attack, so every row holds exactly one. The search becomes choosing a column for row 1, then row 2, and so on.
In the current row, try the columns from left to right. For each, check the queens already placed above: same column, or a diagonal, meaning the column gap equals the row gap. Rows below are still empty, so they need no check.
At the first safe column, place the queen and recurse into the next row. If that was the last row, all N queens are placed and the puzzle is solved.
If no column in a row is safe, return false. The row above lifts its queen and carries on from its next column to the right.
The page opens at N = 4 (the slider goes up to 8) and counts rows and columns from 1. Row 1 takes column 1. Row 2 finds columns 1 and 2 attacked and takes column 3. Row 3 is attacked in all 4 columns, so row 2 moves on to column 4. Row 3 now takes column 2, but row 4 has no safe square; row 3 tries columns 3 and 4, both attacked, and gives up, and row 2 has no columns left either. So row 1 moves to column 2. From there row 2 takes column 4, row 3 column 1 and row 4 column 3. The answer is columns 2, 4, 1, 3, reached after 26 tries and 4 backtracks. At N = 8 the same search needs 876 tries and 105 backtracks and finishes on columns 1, 5, 8, 6, 3, 7, 2, 4.
The page stops at the first answer. To list them all, record the board when the last row is filled and keep searching instead of returning. N = 4 has 2 answers, N = 6 has 4 and N = 8 has 92. N = 2 and N = 3 have none.
Time: row 1 has N columns to try, row 2 at most N - 1 that are not in a used column, and so on, which bounds the search by N! placements; the diagonal checks prune far more in practice. Space: the recursion is at most N rows deep and the queens fit in one column number per row; this page also keeps the full N by N board for drawing, which is O(N²).