ProgrammingVery hardCompetitive coding (CP)

How many placements of 4 queens on a 4 by 4 board have no two queens attacking each other? The program counts them by backtracking. What is printed?

How many placements of 4 queens on a 4 by 4 board have no two queens attacking each other? The program counts them by backtracking. What is printed?
#include <stdio.h>
int n = 4, cnt = 0;
int col[4], d1[8], d2[8];
void place(int r) {
    if (r == n) { cnt++; return; }
    for (int c = 0; c < n; c++) {
        if (col[c] || d1[r + c] || d2[r - c + n - 1]) continue;
        col[c] = d1[r + c] = d2[r - c + n - 1] = 1;
        place(r + 1);
        col[c] = d1[r + c] = d2[r - c + n - 1] = 0;
    }
}
int main(void) {
    place(0);
    printf("%d", cnt);
}
  1. A. 2
  2. B. 4
  3. C. 1
  4. D. 0

Correct answer: A. 2

The backtracking finds exactly two safe placements of four queens on a 4 by 4 board, which are mirror images of each other. Dropping the diagonal checks would give a larger count.

More C Programming questions

Exams that ask this topic