Algorithms · Visualized

N-Queens

Backtracking

Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.

Place N chess queens on an N×N board so that no two queens attack each other (no shared row, column, or diagonal). Time: O(N!) roughly, heavily pruned by safety checks average, O(N!) worst; space: O(N) — recursion depth and board state tracking.

Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.

N-Queens

Backtracking

Place N chess queens on an N×N board so that no two queens attack each other (no shared row, column, or diagonal). Backtracking places queens one row at a time: for each row, try every column, check if it's safe given previously placed queens, and backtrack if no column works.

How N-Queens Works

  1. Process the board one row at a time, starting at row 0.
  2. For the current row, try placing a queen in each column one by one.
  3. Check if this placement is safe: no other queen already placed shares this column or either diagonal.
  4. If safe, place the queen and recurse to solve the next row.
  5. If all rows are filled, record this as a valid solution; if a row has no safe column, backtrack — remove the last placed queen and try the next column in the previous row.

N-Queens Worked Example

Input: 4

Row0: place queen at col1. Row1: col0,col2,col3 all attacked → dead end, backtrack row0 to col2. Row1: col0 safe → place. Row2: col1,col2,col3 attacked... eventually col? none safe → backtrack. Continue searching; for N=4 the two valid solutions found are queens at columns [1,3,0,2] and [2,0,3,1].

N-QueensO(n!)
Place n queens with no two attacking — prune by column and diagonal.
Q
solutions0
queens1
Step 1 / 79
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Place Q at (0,0)
Python · Backtracking in Code
def n_queens(n):
    cols, d1, d2 = set(), set(), set()
    out, board = [], [['.'] * n for _ in range(n)]
    def place(r):
        if r == n:
            out.append([''.join(row) for row in board])
            return
        for c in range(n):
            if c in cols or r - c in d1 or r + c in d2:
                continue
            cols.add(c); d1.add(r - c); d2.add(r + c)
            board[r][c] = 'Q'
            place(r + 1)
            board[r][c] = '.'
            cols.remove(c); d1.remove(r - c); d2.remove(r + c)
    place(0)
    return out

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

N-Queens Time & Space Complexity

BestVaries
AverageO(N!) roughly, heavily pruned by safety checks
WorstO(N!)
SpaceO(N) — recursion depth and board state tracking

When to Use N-Queens

  • A classic constraint-satisfaction problem showcasing pruning in backtracking (checking safety before recursing, not after).
  • Techniques generalize to any placement problem with row/column/region exclusion rules, like Sudoku solvers.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.