请写一段c++代码实现数独游戏
时间: 2024-03-05 11:55:19 浏览: 21
好的,以下是一个简单的 C++ 数独游戏实现代码,希望能够帮到您:
```c++
#include <iostream>
using namespace std;
const int N = 9;
bool row[N][N], col[N][N], block[N][N];
int board[N][N];
int get_block_index(int row, int col) {
return row / 3 * 3 + col / 3;
}
bool dfs(int x, int y) {
if (x == N) return true;
if (y == N) return dfs(x + 1, 0);
if (board[x][y] != 0) return dfs(x, y + 1);
for (int i = 1; i <= 9; i++) {
if (row[x][i] || col[y][i] || block[get_block_index(x, y)][i]) continue;
row[x][i] = col[y][i] = block[get_block_index(x, y)][i] = true;
board[x][y] = i;
if (dfs(x, y + 1)) return true;
row[x][i] = col[y][i] = block[get_block_index(x, y)][i] = false;
board[x][y] = 0;
}
return false;
}
int main() {
// 初始化
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> board[i][j];
if (board[i][j] != 0) {
row[i][board[i][j]] = true;
col[j][board[i][j]] = true;
block[get_block_index(i, j)][board[i][j]] = true;
}
}
}
// 求解
dfs(0, 0);
// 输出结果
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
在这个例子中,我们使用深度优先搜索 (DFS) 的方式来求解数独。在搜索的过程中,我们需要判断当前位置是否已经有数字,如果已经有数字,则直接跳过;否则,我们从 1 到 9 枚举每一个可能的数字,判断该数字是否可以放在当前位置。如果不能放,我们直接跳过;如果可以放,我们将该数字放在当前位置并标记该数字在该行、该列、该九宫格中已经出现过。然后,我们递归地搜索下一个位置,如果找到了解,则返回 true;否则,我们需要回溯,恢复之前的状态,然后继续枚举下一个数字。
希望这个例子能够帮到您,如果您有任何问题,请随时问我。