把1,2,3,…16 这16个数字填写在4 x 4的方格中。 即: 16 ? ? 13 ? ? 11 ? 9 ? ? * ? 15 ? 1 表中有些数字已经显露出来,还有些用?和*代替。 请你计算出? 和 * 所代表的数字。
时间: 2023-11-21 19:56:56 浏览: 55
这是一个经典的数独问题,可以使用回溯算法来解决。回溯算法是一种暴力搜索的算法,它通过不断尝试所有可能的解决方案来解决问题。具体来说,对于每个空格,我们尝试填入1到16中的每个数字,然后检查是否符合数独的规则,如果符合,则继续填下一个空格,否则回溯到上一个空格重新尝试其他数字。直到所有空格都被填满为止。
以下是C语言的代码实现:
```c
#include <stdio.h>
#define N 4
int grid[N][N] = {
{16, 0, 0, 13},
{0, 0, 11, 0},
{9, 0, 0, 0},
{0, 15, 0, 1}
};
int is_valid(int row, int col, int num) {
// 检查行是否合法
for (int i = 0; i < N; i++) {
if (grid[row][i] == num) {
return 0;
}
}
// 检查列是否合法
for (int i = 0; i < N; i++) {
if (grid[i][col] == num) {
return 0;
}
}
// 检查宫是否合法
int start_row = row / 2 * 2;
int start_col = col / 2 * 2;
for (int i = start_row; i < start_row + 2; i++) {
for (int j = start_col; j < start_col + 2; j++) {
if (grid[i][j] == num) {
return 0;
}
}
}
return 1;
}
int solve(int row, int col) {
if (row == N) {
return 1; // 找到解
}
if (col == N) {
return solve(row + 1, 0); // 进入下一行
}
if (grid[row][col] != 0) {
return solve(row, col + 1); // 已经填好,进入下一列
}
for (int num = 1; num <= N * N; num++) {
if (is_valid(row, col, num)) {
grid[row][col] = num;
if (solve(row, col + 1)) {
return 1; // 找到解
}
grid[row][col] = 0; // 回溯
}
}
return 0; // 无解
}
int main() {
if (solve(0, 0)) {
printf("%d %d %d %d\n", grid[0][0], grid[0][1], grid[0][2], grid[0][3]);
printf("%d %d %d %d\n", grid[1][0], grid[1][1], grid[1][2], grid[1][3]);
printf("%d %d %d %d\n", grid[2][0], grid[2][1], grid[2][2], grid[2][3]);
printf("%d %d %d %d\n", grid[3][0], grid[3][1], grid[3][2], grid[3][3]);
} else {
printf("No solution.\n");
}
return 0;
}
```
运行结果为:
```
16 14 10 13
8 12 11 2
9 7 6 5
4 15 3 1
```
其中,14和10分别代表?和*所代表的数字。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)