用c语言写个数独游戏代码
时间: 2023-03-29 08:03:00 浏览: 149
好的,我可以回答这个问题。以下是一个简单的数独游戏代码示例:
#include <stdio.h>
#define N 9
#define UNASSIGNED
int grid[N][N] = {
{3, , 6, 5, , 8, 4, , },
{5, 2, , , , , , , },
{, 8, 7, , , , , 3, 1},
{, , 3, , , , , 2, },
{9, , , 8, , , , , 5},
{, 5, , , , , 6, , },
{1, 3, , , , , 2, 5, },
{, , , , , , , 7, 4},
{, , 5, 2, , 6, 3, , }
};
int find_unassigned_location(int *row, int *col) {
for (*row = ; *row < N; (*row)++) {
for (*col = ; *col < N; (*col)++) {
if (grid[*row][*col] == UNASSIGNED) {
return 1;
}
}
}
return ;
}
int used_in_row(int row, int num) {
for (int col = ; col < N; col++) {
if (grid[row][col] == num) {
return 1;
}
}
return ;
}
int used_in_col(int col, int num) {
for (int row = ; row < N; row++) {
if (grid[row][col] == num) {
return 1;
}
}
return ;
}
int used_in_box(int box_start_row, int box_start_col, int num) {
for (int row = ; row < 3; row++) {
for (int col = ; col < 3; col++) {
if (grid[row + box_start_row][col + box_start_col] == num) {
return 1;
}
}
}
return ;
}
int is_safe(int row, int col, int num) {
return !used_in_row(row, num) && !used_in_col(col, num) && !used_in_box(row - row % 3, col - col % 3, num);
}
int solve_sudoku() {
int row, col;
if (!find_unassigned_location(&row, &col)) {
return 1;
}
for (int num = 1; num <= 9; num++) {
if (is_safe(row, col, num)) {
grid[row][col] = num;
if (solve_sudoku()) {
return 1;
}
grid[row][col] = UNASSIGNED;
}
}
return ;
}
void print_grid() {
for (int row = ; row < N; row++) {
for (int col = ; col < N; col++) {
printf("%d ", grid[row][col]);
}
printf("\n");
}
}
int main() {
if (solve_sudoku()) {
print_grid();
} else {
printf("No solution exists");
}
return ;
}
阅读全文