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);
}- A. 2
- B. 4
- C. 1
- 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
- What is printed? c #include <stdio.h> int der(int n) { if (n == 0) return 1; if (n == 1) return 0; return (n - 1) (der(n - 1) + der(n…
- How many subsets of {1, 2, 3, 4, 5} sum to 6? Compute with this recursive program. c #include <stdio.h> int v[5] = {1, 2, 3, 4, 5}; int…
- What is printed? Assume uint8t is 8 bits. c #include <stdint.h> #include <stdio.h> int main(void) { uint8t x = 0x1C; int c = 0; for (int i…
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 3, r = 0; for (int i = 0; i < 4; i++) { r = (r << 1) | (x & 1u); x >>=…
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 0xABCD, p = 0; while (x) { p ^= x & 1u; x >>= 1; } / p is the parity…
- What is printed? c #include <stdint.h> #include <stdio.h> int main(void) { uint32t a = 0xFFFFFFF0u, b = 0x20u; uint32t s = a + b; int…