使用C语言实现一个数独生成器,可以随机生成数独题,并调试输出。
时间: 2024-03-03 10:49:47 浏览: 94
好的,以下是一个简单的数独生成器的 C 语言实现。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 9
#define EMPTY 0
void print_board(int board[N][N]) {
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}
}
int is_valid(int board[N][N], int row, int col, int num) {
int i, j;
// Check row
for (i = 0; i < N; i++) {
if (board[row][i] == num) {
return 0;
}
}
// Check column
for (j = 0; j < N; j++) {
if (board[j][col] == num) {
return 0;
}
}
// Check block
int start_row = row - row % 3;
int start_col = col - col % 3;
for (i = start_row; i < start_row + 3; i++) {
for (j = start_col; j < start_col + 3; j++) {
if (board[i][j] == num) {
return 0;
}
}
}
return 1;
}
int solve_board(int board[N][N]) {
int row, col, num;
for (row = 0; row < N; row++) {
for (col = 0; col < N; col++) {
if (board[row][col] == EMPTY) {
for (num = 1; num <= N; num++) {
if (is_valid(board, row, col, num)) {
board[row][col] = num;
if (solve_board(board)) {
return 1;
} else {
board[row][col] = EMPTY;
}
}
}
return 0;
}
}
}
return 1;
}
void generate_board(int board[N][N], int difficulty) {
int i, j, row, col, num, temp_board[N][N], count = 0;
srand(time(NULL));
// Generate a solved board
for (row = 0; row < N; row++) {
for (col = 0; col < N; col++) {
temp_board[row][col] = EMPTY;
}
}
solve_board(temp_board);
// Copy the solved board to the actual board
for (row = 0; row < N; row++) {
for (col = 0; col < N; col++) {
board[row][col] = temp_board[row][col];
}
}
// Remove some numbers to create a puzzle
while (count < difficulty) {
row = rand() % N;
col = rand() % N;
if (board[row][col] != EMPTY) {
num = board[row][col];
board[row][col] = EMPTY;
// Check if there is still a unique solution
int temp_board[N][N];
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
temp_board[i][j] = board[i][j];
}
}
int solutions = 0;
solve_board(temp_board);
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (temp_board[i][j] == EMPTY) {
solutions++;
}
}
}
if (solutions != 1) {
board[row][col] = num;
} else {
count++;
}
}
}
}
int main() {
int board[N][N], difficulty;
printf("Enter difficulty level (1-5): ");
scanf("%d", &difficulty);
generate_board(board, difficulty * 10);
print_board(board);
return 0;
}
```
这个程序使用回溯算法来解决数独问题。它首先生成一个解决方案,然后从中删除一些数字以创建随机的数独题。在 `generate_board` 函数中,`difficulty` 参数表示难度级别,它控制了要删除的数字的数量。在 `main` 函数中,程序要求用户输入难度级别,并使用 `generate_board` 函数生成一个数独题。最后,程序使用 `print_board` 函数打印出生成的数独题。
希望这个程序对您有所帮助!
阅读全文