Placing a Million Queens in a Tenth of a Second
The N-queens puzzle asks you to place N queens on an N × N board so that no two attack each other. Counting every solution is hard. The number grows faster than exponentially: Michael Simkin showed in 2021 that it is roughly (0.143 N)N, and exact counts are known only for small boards. Finding one solution is a different problem entirely. With the right search, a desktop machine finds one for a million queens in well under a second.
This post describes such a search and gives a complete C program for it. If the puzzle is new to you, the Wikipedia article is a good introduction.
A small example#
For N = 4 there are exactly two solutions (1 marks a queen):
0100 0010
0001 1000
1000 0001
0010 0100
Backtracking finds these instantly, but plain backtracking slows to a crawl long before N reaches the thousands. Local search does not explore the board systematically. It starts from a nearly correct placement and repairs it.
One caveat before going further. If all you need is a solution, you do not need search at all: explicit constructions produce one for every N ≥ 4 in linear time, and they are far faster than anything in this post (see the comparison at the end). Local search is still worth studying, because the same ideas solve constraint problems that have no closed form, from scheduling to SAT, and the N-queens puzzle is the cleanest place to see them work.
The algorithm#
Representation. Every row holds exactly one queen, so a placement is just an array: queen[i] = j means the queen in row i stands in column j. If queen is a permutation of 1..N, no two queens share a row or a column. The only conflicts left are diagonal ones.
Counting conflicts. Number the anti-diagonals by row + column (2 to 2N) and the diagonals by column − row (1 − N to N − 1). Two arrays, dn and dp, count the queens on each. The cost function collisions adds up, over all diagonals, the queens beyond the first. A placement is a solution exactly when collisions is zero.
Moves. The only move is to swap the columns of two rows. A swap keeps queen a permutation and touches just four diagonals, so its effect on collisions costs constant time to compute.
A good start. Most of the speed comes from the initial placement. Row by row, the program picks a random column among those not yet used and keeps it only if it attacks none of the queens already placed. After 4N attempts it stops being picky and places the remaining queens at random. For large N this greedy start leaves only a handful of conflicts, so the search that follows is short.
Hill climbing. The program keeps a list of the queens under attack. For each one it picks a random partner and swaps the two if that lowers collisions. Rebuilding the list after every swap would dominate the running time, so it is rebuilt only when collisions falls below half its value at the previous rebuild.
Restarts. If about 32N attempts pass without reaching zero, the search is stuck in a local minimum, and the program starts over from a fresh random placement.
The method is essentially the conflict-minimizing local search of Rok Sosič and Jun Gu, described in Efficient Local Search with Conflict Minimization: A Case Study of the n-Queens Problem (IEEE TKDE, 1994).
The program#
The program takes N on the command line and, optionally, a file to write the solution to: the column of each row, followed by a drawing of the board when N ≤ 20. It checks the solution independently before reporting success.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// queen[i] = j: the queen in row i stands in column j (both numbered from 1).
// dn[k]: number of queens on the anti-diagonal k = row + column, k in [2, 2n].
// dp[k]: number of queens on the diagonal k = column - row, k in [1-n, n-1].
// attack[]: rows whose queen is currently under attack.
static int n;
static int *queen, *dn, *dp, *attack;
static long collisions; // queens beyond the first on each diagonal, summed
static uint64_t rng_state;
// 64-bit linear congruential generator (Knuth's MMIX constants);
// only the high 32 bits are used.
static uint32_t next_random(void)
{
rng_state = rng_state * 6364136223846793005ULL + 1442695040888963407ULL;
return (uint32_t)(rng_state >> 32);
}
// A random integer in [0, k).
static int random_below(int k)
{
return (int)(next_random() % (uint32_t)k);
}
static void swap_int(int *p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;
}
// Take the queen in `row` off the board.
static void remove_queen(int row)
{
int col = queen[row];
if (--dn[col + row] >= 1) // the diagonal still holds another queen
--collisions;
if (--dp[col - row] >= 1)
--collisions;
}
// Put the queen of `row` in column `col`.
static void place_queen(int row, int col)
{
queen[row] = col;
if (dn[col + row]++ >= 1) // the diagonal was already occupied
++collisions;
if (dp[col - row]++ >= 1)
++collisions;
}
// Swap the queens of rows i and j, keeping dn, dp and collisions exact.
static void swap_queens(int i, int j)
{
int ci = queen[i], cj = queen[j];
remove_queen(i);
remove_queen(j);
place_queen(i, cj);
place_queen(j, ci);
}
static int is_attacked(int row)
{
return dn[queen[row] + row] > 1 || dp[queen[row] - row] > 1;
}
// Rebuild attack[] and return the number of queens under attack.
static int compute_attack(void)
{
int k = 0;
for (int i = 1; i <= n; ++i)
if (is_attacked(i))
attack[++k] = i;
return k;
}
// Build the initial placement.
static void initialize(void)
{
for (int k = 2; k <= 2 * n; ++k)
dn[k] = 0;
for (int k = 1 - n; k <= n - 1; ++k)
dp[k] = 0;
collisions = 0;
for (int i = 1; i <= n; ++i)
queen[i] = i;
// Start as close to a solution as possible, so the climb is short:
// fill rows in order, each time trying a random unused column and
// keeping it only if it conflicts with nothing placed so far.
// j is the next row to fill; at most 4n attempts are made.
long search_max = 4L * n;
int j = 1;
for (long i = 1; i <= search_max && j <= n; ++i)
{
int m = j + random_below(n - j + 1); // random m in [j, n]
if (dn[queen[m] + j] == 0 && dp[queen[m] - j] == 0)
{
swap_int(&queen[m], &queen[j]);
place_queen(j, queen[j]);
++j;
}
}
// Shuffle the remaining columns into the remaining rows.
for (int i = j; i <= n; ++i)
{
int m = i + random_below(n - i + 1);
swap_int(&queen[m], &queen[i]);
place_queen(i, queen[i]);
}
}
// Find one solution: initialize, hill-climb, restart when stuck.
static void solve(void)
{
for (;;)
{
initialize();
if (collisions == 0)
return;
// Rebuilding attack[] after every swap is too expensive;
// rebuild it only once collisions has fallen below `limit`.
long limit = collisions / 2;
int number_of_attacks = compute_attack();
// A large loopcount means the climb is stuck in a local minimum.
long loopcount = 0;
while (loopcount < 32L * n)
{
for (int k = 1; k <= number_of_attacks; ++k)
{
// Try swapping an attacked queen with a random one.
int i = attack[k];
int j = 1 + random_below(n);
if (i == j)
continue;
long before = collisions;
swap_queens(i, j);
if (collisions >= before)
{
swap_queens(i, j); // no improvement: undo
continue;
}
if (collisions == 0)
return;
if (collisions < limit)
{
// The board has changed enough to refresh the list.
limit = collisions / 2;
number_of_attacks = compute_attack();
}
}
loopcount += number_of_attacks;
}
}
}
// Check the answer from scratch: one queen per column, at most one per diagonal.
static int verify(void)
{
char *col = calloc((size_t)n + 1, 1);
char *d1 = calloc(2 * (size_t)n + 1, 1);
char *d2 = calloc(2 * (size_t)n + 1, 1);
int ok = col && d1 && d2;
for (int i = 1; ok && i <= n; ++i)
{
int c = queen[i];
if (c < 1 || c > n || col[c] || d1[c + i] || d2[c - i + n])
ok = 0;
else
col[c] = d1[c + i] = d2[c - i + n] = 1;
}
free(col);
free(d1);
free(d2);
return ok;
}
int main(int argc, char **argv)
{
if (argc < 2 || (n = atoi(argv[1])) < 1 || n > 100000000)
{
fprintf(stderr, "usage: %s N [output-file] (1 <= N <= 100000000)\n", argv[0]);
return 1;
}
if (n == 2 || n == 3)
{
printf("no solution for N = %d\n", n);
return 0;
}
// Rows and columns are numbered from 1, so queen, attack and dn simply
// leave their first slots unused. dp is indexed from 1-n to n-1, so it
// points into the middle of its buffer: dp[1-n] is pre_dp[0].
// (Pointing *before* a buffer would be undefined behaviour in C.)
queen = malloc(sizeof(int) * ((size_t)n + 1));
attack = malloc(sizeof(int) * ((size_t)n + 1));
dn = malloc(sizeof(int) * (2 * (size_t)n + 1));
int *pre_dp = malloc(sizeof(int) * (2 * (size_t)n - 1));
if (!queen || !attack || !dn || !pre_dp)
{
fprintf(stderr, "out of memory\n");
return 1;
}
dp = pre_dp + (n - 1);
rng_state = (uint64_t)time(NULL);
clock_t start = clock();
solve();
clock_t end = clock();
printf("N = %d: found a solution in %.3f seconds (%s)\n", n,
(double)(end - start) / CLOCKS_PER_SEC, verify() ? "verified" : "INVALID");
if (argc >= 3)
{
FILE *fp = fopen(argv[2], "w");
if (!fp)
{
perror(argv[2]);
return 1;
}
// The i-th number is the column of the queen in row i; for N <= 20,
// also draw the board (* is a queen).
for (int i = 1; i <= n; ++i)
fprintf(fp, "%d%c", queen[i], i == n ? '\n' : ' ');
if (n <= 20)
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
fputc(j == queen[i] ? '*' : '-', fp);
fputc('\n', fp);
}
fclose(fp);
}
free(queen);
free(attack);
free(dn);
free(pre_dp);
return 0;
}
Build and run it:
$ cc -O2 -o nqueens nqueens.c
$ ./nqueens 8 out.txt
N = 8: found a solution in 0.000 seconds (verified)
$ cat out.txt
5 1 8 6 3 7 2 4
----*---
*-------
-------*
-----*--
--*-----
------*-
-*------
---*----
$ ./nqueens 1000000
N = 1000000: found a solution in 0.060 seconds (verified)
The seed comes from the clock, so each run usually prints a different solution. The timings were measured on an AMD Ryzen 9 9950X. The running time is not linear in N. Going from 100,000 to 1,000,000 queens multiplies it by about 14 (4 ms to 58 ms), and going on to 10,000,000 multiplies it by about 32 (to 1.8 s). The algorithm is not to blame. Hardware counters (perf stat, whole program including the final check) show the instruction count growing almost exactly in proportion to N, 21 million at N = 100,000 and 2.0 billion at N = 10,000,000, while the cycle count grows from 21 million to 10.4 billion. Instructions per cycle fall from about 1.0 to 0.19. Every swap touches rows and diagonals at random, and at ten million queens the four arrays occupy about 240 MB, far more than any cache, so the processor spends most of its time waiting for memory. Making the solver faster for very large N is a data-layout problem, not a search problem.
How it compares with a formula#
The simplest explicit construction lists the even columns, then the odd ones, with a small adjustment when N mod 6 is 2 or 3. I implemented it, checked it with the same verifier for every N from 4 to 3,000, and timed it against the search on the same machine:
| N | Local search | Explicit construction |
|---|---|---|
| 1,000,000 | 0.056 s | 0.001 s |
| 10,000,000 | 1.9 s | 0.007–0.018 s |
| 100,000,000 | 25 s | 0.07–0.18 s |
The construction wins by two orders of magnitude, and the gap widens with N. It writes each entry of queen exactly once, in order, so it runs at the speed of sequential memory writes, while the search makes random accesses that miss the cache. (The construction’s timings vary by N mod 6 and from run to run, probably because of first-touch page faults.) Use the formula when you need a solution; use the search when you need to understand local search.
What the first version got wrong#
I wrote the first version of this program in 2020. Revisiting it in 2026 turned up three bugs worth recording, because each one is easy to make:
- An overflowing random index. The partner for a swap came from
((rand() << 6) + rand()) % n + 1. With glibc,RAND_MAXis 231 − 1, so the shift overflowsint. That is undefined behaviour, and in practice the index went negative and the program wrote outside its arrays. For large N it printed “solutions” that were not even permutations. The program now carries its own 64-bit generator. - An inexact shortcut. The change in
collisionscaused by a swap was computed with a closed-form formula that is wrong when the two queens share a diagonal, so the running count drifted away from the truth. A swap is now applied as “remove both queens, put them back exchanged”, and undone if it does not help. That costs a few more memory accesses and is always exact. - Missing edge cases. The arrays were sized for 123,456,789 queens regardless of N, and N = 2 or N = 3, which have no solution, looped forever.
The program also verifies its answer independently now. Had the original done that, the first bug would have surfaced on the first large run.