用c语言代码写一个数独游戏
时间: 2023-09-14 09:02:51 浏览: 160
好的,以下是用C语言实现的数独游戏代码:
```c
#include <stdio.h>
#include <stdbool.h>
#define SIZE 9
bool is_row_valid(int sudoku[][SIZE], int row, int num) {
for (int col = 0; col < SIZE; col++) {
if (sudoku[row][col] == num) {
return false;
}
}
return true;
}
bool is_col_valid(int sudoku[][SIZE], int col, int num) {
for (int row = 0; row < SIZE; row++) {
if (sudoku[row][col] == num) {
return false;
}
}
return true;
}
bool is_box_valid(int sudoku[][SIZE], int start_row, int start_col, int num) {
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
if (sudoku[row + start_row][col + start_col] == num) {
return false;
}
}
}
return true;
}
bool is_valid(int sudoku[][SIZE], int row, int col, int num) {
return is_row_valid(sudoku, row, num) &&
is_col_valid(sudoku, col, num) &&
is_box_valid(sudoku, row - row % 3, col - col % 3, num);
}
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},
};
if (solve_sudoku(sudoku)) {
print_sudoku(sudoku);
} else {
printf("No solution found.\n");
}
return 0;
}
```
这个程序实现了数独游戏的求解功能,可以通过修改 `sudoku` 数组中的初始值来设置不同的数独谜题。
阅读全文