Python coding

Queens that never attack

Place n chess queens on an n × n board so that no two attack each other: no two may share a row, a column or a diagonal. Return every such placement. Each row then holds exactly one queen, so write a placement as a list cols where cols[r] is the column (0-based) of the queen in row r. Return each placement once, in any order; if there is none, return an empty list.

1 ≤ n ≤ 9.

  • queen_placements(4) → [[1,3,0,2],[2,0,3,1]]
  • queen_placements(1) → [[0]]
  • queen_placements(3) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Fill the board row by row: level r of the recursion chooses the column of the queen in row r, so two queens can never share a row.

Hint 2

Cells on one diagonal share r - c, on the other r + c. Mark taken columns and diagonals in three boolean lists (or sets); skip a marked cell, otherwise mark it, recurse, then unmark it.

Hint 3

Checking complete placements is the trap: n! column orders, most doomed by a clash in their first rows. Reject a queen the moment it is attacked, and its whole subtree disappears.

Solution and why it works
pythonO(n!) at most; pruning keeps the search far smaller · O(n) for the marks and the recursion, beyond the output
def queen_placements(n: int) -> list[list[int]]:
    col = [False] * n
    diag = [False] * (2 * n)             # r - c + n: one value per ↘ diagonal
    anti = [False] * (2 * n)             # r + c: one value per ↙ diagonal
    res, path = [], []

    def bt(r: int) -> None:
        if r == n:
            res.append(path[:])          # a queen in every row: one placement
            return
        for c in range(n):
            if col[c] or diag[r - c + n] or anti[r + c]:
                continue                 # prune: this cell is attacked
            col[c] = diag[r - c + n] = anti[r + c] = True
            path.append(c)
            bt(r + 1)
            path.pop()
            col[c] = diag[r - c + n] = anti[r + c] = False   # undo, or ghosts stay

    bt(0)
    return res

Cells on one diagonal share r - c and on the other r + c, so three lookups (column and both diagonals) tell in O(1) whether a cell is attacked. With one queen per row and attacked cells rejected at once, a branch dies at its first clash, and every path that reaches row n is a placement. The trap is generate-then-test: checking all n! column orders redoes the work for each doomed prefix. Undo all three marks on the way back, or later branches see ghost queens.