写一个C语言实现的八皇后代码
时间: 2024-05-04 18:15:37 浏览: 170
Sure, here's the C code for solving the eight queens problem:
```
#include <stdio.h>
#define N 8
int board[N][N];
int is_valid(int row, int col) {
int i, j;
for (i = 0; i < col; i++)
if (board[row][i])
return 0;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return 0;
for (i = row, j = col; i < N && j >= 0; i++, j--)
if (board[i][j])
return 0;
return 1;
}
int solve(int col) {
int i;
if (col >= N)
return 1;
for (i = 0; i < N; i++) {
if (is_valid(i, col)) {
board[i][col] = 1;
if (solve(col + 1))
return 1;
board[i][col] = 0;
}
}
return 0;
}
int main() {
int i, j;
if (solve(0)) {
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
printf("%2d", board[i][j]);
printf("\n");
}
} else {
printf("No solution found.\n");
}
return 0;
}
```
This program uses recursive backtracking to find a solution to the eight queens problem. The `board` array represents the chess board, where `1` indicates a queen is placed, and `0` indicates an empty square. The `is_valid` function checks whether a queen can be placed in a given row and column, without violating the rules of chess. The `solve` function tries to place queens on the board, one column at a time, until a solution is found or deemed impossible. The `main` function simply calls `solve` and prints the resulting board if a solution is found.
阅读全文