data-structures · intermediate · ~15 min

Count N-Queens solutions

Place n non-attacking queens by backtracking.

Challenge

Implement:

int count_n_queens(int n);

Return the number of ways to place n non-attacking queens on an n x n board, using backtracking. 1 <= n <= 12.

Input format

n in [1,12].

Output format

Number of solutions.

Constraints

Track used columns and both diagonals.

Starter code

#include <stddef.h>
/* Number of ways to place n non-attacking queens on an n x n board (backtracking). 1<=n<=12. */
int count_n_queens(int n){ (void)n; return 0; }

Common mistakes

Not un-marking state when backtracking; wrong diagonal indices.

Edge cases to handle

n=2 and n=3 have 0 solutions.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.