N-Queens visualization

Place N queens so none attack each other; undo a placement when it leads to a dead end.

Place one queen per row. For each column, check whether it is attacked along the column or a diagonal. If safe, recurse to the next row; if no column works, backtrack and move the previous queen.

Edge cases: N = 1 is trivially solvable; N = 2 and N = 3 have no solution at all — the search exhausts every option and reports failure.

Complexity

Time: best O(N!), average O(N!), worst O(N!). Space: O(N). Difficulty: Intermediate.

Pseudocode

procedure solve(row):
  if row = N: return true              // all queens placed
  for col ← 0 to N−1:
    if safe(row, col):
      place queen at (row, col)
      if solve(row + 1): return true
      remove queen (backtrack)
  return false

More backtracking algorithms