Skip to interview prep
Apexed

78. How does the backtracking solution to N-Queens work?

HardRecursion & backtracking

Technical

Type or dictate your answer. Your draft is saved on this device.

Show model answer

Place one queen per row. For row r, try each column c that is not attacked: keep three sets (or boolean arrays) for used columns, used "r - c" diagonals and used "r + c" anti-diagonals so the check is O(1). Place the queen, recurse to row r+1, then remove it. Reaching row n means a full solution.

The search is far smaller than n^n because invalid partial boards are abandoned immediately; the worst case is bounded by about O(n!). Space is O(n). Bitmask versions are faster in practice. There are 2 solutions for n = 4 and 92 for n = 8.

Example program

How does the backtracking solution to N-Queens work — Data structures & algorithms interview question — Apexed