Little Bishops Problem in C
The "Little Bishops" problem is a classic chess puzzle where you need to place bishops on an N×N chessboard such that no two bishops attack each other. Here's a C implementation that solves this problem:

#include <stdio.h>
#include <stdlib.h>
int count = 0;
// Function to check if a position is safe for placing a bishop
int isSafe(int board[], int row, int col) {
for (int i = 0; i < row; i++) {
// Check if there's a bishop in the same diagonal
if (abs(board[i] - col) == abs(i - row)) {
return 0;
}
}
return 1;
}
// Recursive function to place bishops
void placeBishops(int board[], int row, int n, int bishopsPlaced) {
if (bishopsPlaced == 0) {
count++;
return;
}
if (row >= n) {
return;
}
for (int col = 0; col < n; col++) {
if (isSafe(board, row, col)) {
board[row] = col;
placeBishops(board, row + 1, n, bishopsPlaced - 1);
}
}
}
// Function to count the number of ways to place bishops
int countBishopPlacements(int n, int k) {
int *board = (int *)malloc(n * sizeof(int));
count = 0;
placeBishops(board, 0, n, k);
free(board);
return count;
}
int main() {
int n, k;
printf("Enter the size of the chessboard (n): ");
scanf("%d", &n);
printf("Enter the number of bishops to place (k): ");
scanf("%d", &k);
if (k > 2 * n - 1) {
printf("It's impossible to place %d bishops on a %dx%d board\n", k, n, n);
return 0;
}
int result = countBishopPlacements(n, k);
printf("Number of ways to place %d bishops on a %dx%d board: %d\n", k, n, n, result);
return 0;
}
How It Works:
-
isSafe(): Checks if placing a bishop at a given position is safe by ensuring no other bishop is in the same diagonal.
-
placeBishops(): A recursive function that tries to place bishops row by row:
- If we've placed all required bishops (k), we increment the count.
- For each row, it tries all possible columns and recursively places bishops in the next row if the position is safe.
-
countBishopPlacements(): Initializes the board and starts the recursive placement process.
-
main(): Takes user input for board size (n) and number of bishops (k), then displays the result.
(图片来源网络,侵删)
Optimization Note:
This basic implementation uses a backtracking approach which works well for small board sizes. For larger boards (n > 10), you might want to implement more optimized solutions using symmetry or mathematical formulas to reduce computation time.
Would you like me to explain any part in more detail or provide an optimized version for larger boards?

