C语言写一个数独游戏,并实现
时间: 2024-03-02 18:48:48 浏览: 140
好的,我可以为您提供一个简单的数独游戏的代码实现,具体如下:
```c
#include <stdio.h>
#include <stdbool.h>
#define SIZE 9
int board[SIZE][SIZE] = {
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}
};
void print_board() {
int i, j;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}
}
bool is_valid(int row, int col, int num) {
int i, j;
// 检查行和列
for (i = 0; i < SIZE; i++) {
if (board[row][i] == num || board[i][col] == num) {
return false;
}
}
// 检查 3x3 方格
int row_start = (row / 3) * 3;
int col_start = (col / 3) * 3;
for (i = row_start; i < row_start + 3; i++) {
for (j = col_start; j < col_start + 3; j++) {
if (board[i][j] == num) {
return false;
}
}
}
return true;
}
bool solve() {
int row, col, num;
for (row = 0; row < SIZE; row++) {
for (col = 0; col < SIZE; col++) {
if (board[row][col] == 0) {
for (num = 1; num <= 9; num++) {
if (is_valid(row, col, num)) {
board[row][col] = num;
if (solve()) {
return true;
} else {
board[row][col] = 0;
}
}
}
return false;
}
}
}
return true;
}
int main() {
// 设置数独终盘
board[0][0] = 5;
board[0][1] = 3;
board[0][4] = 7;
board[1][0] = 6;
board[1][3] = 1;
board[1][4] = 9;
board[1][5] = 5;
board[2][1] = 9;
board[2][2] = 8;
board[2][7] = 6;
board[3][0] = 8;
board[3][4] = 6;
board[3][8] = 3;
board[4][0] = 4;
board[4][3] = 8;
board[4][5] = 3;
board[4][8] = 1;
board[5][0] = 7;
board[5][4] = 2;
board[5][8] = 6;
board[6][1] = 6;
board[6][6] = 2;
board[6][7] = 8;
board[7][3] = 4;
board[7][4] = 1;
board[7][5] = 9;
board[7][8] = 5;
board[8][4] = 8;
board[8][7] = 7;
board[8][8] = 9;
// 打印初始数独
printf("Initial board:\n");
print_board();
// 解数独
if (solve()) {
printf("Solved board:\n");
print_board();
} else {
printf("No solution found.\n");
}
return 0;
}
```
这个程序实现了一个简单的数独游戏,使用了递归的方式解决数独问题。您可以先将终盘的数字修改,尝试自己解决数独,或者可以修改程序实现生成数独、计时等功能。
阅读全文