sagelearnai

N-Queens

Difficulty: Hard · Pattern: Backtracking · LeetCode #51

Place n queens on an n × n chessboard so that no two attack each other (no shared row, column or diagonal). Return all distinct solutions; each is a list of n strings where 'Q' is a queen and '.' is empty. The solutions may be in any order.

Examples

text
n = 4  →  [[".Q..", "...Q", "Q...", "..Q."],
           ["..Q.", "Q...", "...Q", ".Q.."]]
n = 1  →  [["Q"]]
n = 3  →  []

Hints

  1. Each row has exactly one queen, so place them row by row.
  2. A square (r, c) is attacked via its column c, its diagonal r − c and its anti-diagonal r + c.
  3. Keep three sets so the "is it safe?" check is O(1).

Approach

Backtrack by row. For row r, try each column c not in cols, not in diag (r − c) and not in anti (r + c). Place the queen (add to all three sets, record c), recurse to r + 1, then remove. When r == n, convert the recorded columns into board strings. The sets make each safety check O(1) and prune huge parts of the search tree.

Complexity

Time: O(n!) upper bound (pruning makes it much faster in practice). Space: O(n).

Python solution
def solveNQueens(n):
    res, queens = [], []
    cols, diag, anti = set(), set(), set()
    def bt(r):
        if r == n:
            res.append(["." * c + "Q" + "." * (n - c - 1) for c in queens])
            return
        for c in range(n):
            if c in cols or (r - c) in diag or (r + c) in anti:
                continue
            cols.add(c); diag.add(r - c); anti.add(r + c); queens.append(c)
            bt(r + 1)
            cols.remove(c); diag.remove(r - c); anti.remove(r + c); queens.pop()
    bt(0)
    return res
JavaScript solution
function solveNQueens(n) {
  const res = [], queens = [], cols = new Set(), diag = new Set(), anti = new Set();
  const bt = (r) => {
    if (r === n) { res.push(queens.map((c) => '.'.repeat(c) + 'Q' + '.'.repeat(n - c - 1))); return; }
    for (let c = 0; c < n; c++) {
      if (cols.has(c) || diag.has(r - c) || anti.has(r + c)) continue;
      cols.add(c); diag.add(r - c); anti.add(r + c); queens.push(c);
      bt(r + 1);
      cols.delete(c); diag.delete(r - c); anti.delete(r + c); queens.pop();
    }
  };
  bt(0);
  return res;
}