问题描述:
对于一个9*9的一组方格,每一行,每一列,3 *3的小方格区域内填入1-9,每个数字只出现一次。
代码编写:
此题与八皇后问题解法非常相同。
#include <iostream>
#include <vector>
using namespace std;
#define N 9
static int count = 0;
//定义一个数独数组,其中0表示需要填入
int shudu[N][N] = {7,3,0,2,1,8,5,0,4,
2,1,0,0,0,9,0,0,3,
5,9,0,0,7,0,2,8,1,
3,4,1,8,6,0,9,2,7,
0,6,0,0,9,0,0,1,0,
9,5,2,0,4,1,8,3,6,
4,7,3,0,8,0,0,5,2,
6,0,0,1,0,0,0,4,9,
1,0,9,5,3,4,0,6,8};
//int shudu[N][N] = {0};
struct pos{
int row;
int col;
};
vector<pos> vt;
//初始化,扫描数组中哪些位置需要填空
void init(){
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
if(shudu[i][j] == 0){
pos p;
p.row = i;
p.col = j;
vt.push_back(p);
}
}
}
}
//打印
void print(int shudu[N][N]){
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
cout<<shudu[i][j]<<", ";
}
cout<<endl;
}
cout<<endl;
}
//检测填入的数是否合法
bool check(int row, int col)
{
bool ret = true;
// 列方向检测
for (int i = 0; i < 9; i++){
if(shudu[i][col] == shudu[row][col] && i != row){
ret = false;
return ret;
}
}
// 行方向检测
for (int j = 0; j < 9; j++){
if(shudu[row][j] == shudu[row][col] && j != col){
ret = false;
return ret;
}
}
// 区域检测
int block_row = row / 3 * 3;
int block_col = col / 3 * 3;
for (int i = block_row; i < block_row + 3; i++)
{
for (int j = block_col; j < block_col + 3; j++)
{
if(shudu[i][j] == shudu[row][col] && i != row && j != col){
ret = false;
return ret;
}
}
}
return ret;
}
void solve(int i){
if(i >= vt.size()){
count++;
cout<<"第 "<<count<<" 种解法:"<<endl;
print(shudu);
// cin.get();
}else{
int row = vt[i].row;
int col = vt[i].col;
for (int a = 1; a <= 9; a++){
shudu[row][col] = a;
if(check(row, col)){
solve(i+1);
}
shudu[row][col] = 0;
}
}
}
int main(){
cout<<"数独:"<<endl;
print(shudu);
init();
solve(0);
return 0;
}
运行结果: