Example 1 — Count and show the first 4-queens solution
Columns are tried left to right, row by row.
#include <stdio.h>
#include <stdlib.h>
#define N 4
static int cols[N], solutions;
static int safe(int row, int col) {
for (int r = 0; r < row; r++)
if (cols[r] == col || abs(cols[r] - col) == row - r) return 0;
return 1;
}
static void place(int row) {
if (row == N) {
if (++solutions == 1) {
printf("first solution:\n");
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++)
printf("%c%s", cols[r] == c ? 'Q' : '.', c + 1 < N ? " " : "");
printf("\n");
}
}
return;
}
for (int col = 0; col < N; col++) {
if (safe(row, col)) {
cols[row] = col;
place(row + 1);
}
}
}
int main(void) {
place(0);
printf("solutions: %d\n", solutions);
return 0;
} How It Works
- Placing the first queen in column 0 leads to no complete solution, so the search moves on.
- The first complete placement puts queens at columns 1, 3, 0, 2.
- The second solution (columns 2, 0, 3, 1) is the mirror image.
