用C++编写一个解数独的完整代码
时间: 2023-09-05 18:09:51 浏览: 61
以下是用C++编写的解数独的完整代码:
```
#include <iostream>
using namespace std;
const int N = 9;
int grid[N][N];
bool isSafe(int row, int col, int num) {
for (int i = 0; i < N; i++) {
if (grid[row][i] == num || grid[i][col] == num) {
return false;
}
}
int rowStart = (row / 3) * 3;
int colStart = (col / 3) * 3;
for (int i = rowStart; i < rowStart + 3; i++) {
for (int j = colStart; j < colStart + 3; j++) {
if (grid[i][j] == num) {
return false;
}
}
}
return true;
}
bool solveSudoku(int row, int col) {
if (row == N - 1 && col == N) {
return true;
}
if (col == N) {
row++;
col = 0;
}
if (grid[row][col] > 0) {
return solveSudoku(row, col + 1);
}
for (int num = 1; num <= N; num++) {
if (isSafe(row, col, num)) {
grid[row][col] = num;
if (solveSudoku(row, col + 1)) {
return true;
}
}
grid[row][col] = 0;
}
return false;
}
void printSudoku() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << grid[i][j] << " ";
}
cout << endl;
}
}
int main() {
cout << "Enter the sudoku grid (0 for empty cells):" << endl;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> grid[i][j];
}
}
if (solveSudoku(0, 0)) {
cout << "Solution:" << endl;
printSudoku();
} else {
cout << "No solution exists." << endl;
}
return 0;
}
```
该代码使用回溯算法来解决数独问题。isSafe()函数检查给定数字是否可以放入给定位置,而solveSudoku()函数使用递归来解决问题。printSudoku()函数用于打印解决方案。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)