用c语言写一个数独游戏
时间: 2023-11-16 22:04:47 浏览: 71
好的,以下是用C语言实现的数独游戏代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 9
bool is_valid(int sudoku[][SIZE], int row, int col, int num) {
// Check if the number is already in the row or column
for (int i = 0; i < SIZE; i++) {
if (sudoku[row][i] == num || sudoku[i][col] == num) {
return false;
}
}
// Check if the number is already in the 3x3 box
int box_row = row - row % 3;
int box_col = col - col % 3;
for (int i = box_row; i < box_row + 3; i++) {
for (int j = box_col; j < box_col + 3; j++) {
if (sudoku[i][j] == num) {
return false;
}
}
}
return true;
}
bool find_unassigned(int sudoku[][SIZE], int *row, int *col) {
for (*row = 0; *row < SIZE; (*row)++) {
for (*col = 0; *col < SIZE; (*col)++) {
if (sudoku[*row][*col] == 0) {
return true;
}
}
}
return false;
}
bool solve_sudoku(int sudoku[][SIZE]) {
int row, col;
if (!find_unassigned(sudoku, &row, &col)) {
return true;
}
for (int num = 1; num <= 9; num++) {
if (is_valid(sudoku, row, col, num)) {
sudoku[row][col] = num;
if (solve_sudoku(sudoku)) {
return true;
}
sudoku[row][col] = 0;
}
}
return false;
}
void print_sudoku(int sudoku[][SIZE]) {
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
printf("%d ", sudoku[row][col]);
}
printf("\n");
}
}
int main() {
int sudoku[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},
};
// Ask the user to input the initial numbers in the sudoku
printf("Enter the initial numbers in the sudoku (0 for unknown cells):\n");
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
scanf("%d", &sudoku[row][col]);
}
}
if (solve_sudoku(sudoku)) {
printf("Solution:\n");
print_sudoku(sudoku);
} else {
printf("No solution found.\n");
}
return 0;
}
```
这个程序实现了数独游戏的求解功能,可以通过用户输入初始值来设置不同的数独谜题。在程序执行时,会要求用户输入一个 9x9 的矩阵,其中已知的数字用数字表示,未知的数字用 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 0
```
这表示所有的数字都未知,程序会输出数独的解。如果用户输入的初始值有多个解,程序会输出其中任意一个解。如果没有解,程序会输出 "No solution found."。
阅读全文