算法很简单
基本就是挨个枚举
#include <iostream>
#include <cmath>
using namespace std;
int a[12][12];
int pl[12][12] = {
{0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,2,2,2,3,3,3},
{0,1,1,1,2,2,2,3,3,3},
{0,1,1,1,2,2,2,3,3,3},
{0,4,4,4,5,5,5,6,6,6},
{0,4,4,4,5,5,5,6,6,6},
{0,4,4,4,5,5,5,6,6,6},
{0,7,7,7,8,8,8,9,9,9},
{0,7,7,7,8,8,8,9,9,9},
{0,7,7,7,8,8,8,9,9,9}
};//(x,y)在pl[x][y]号宫
void show() {
cout<<"\033[100A\033[0m";
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++)
cout << a[i][j] << ' ';
cout << endl;
}
cout<<" "<<endl<<" "<<endl;
}//输出结果
//尝试x行y列的格子,并递归进入下一个
bool r[10][10] = {{0}};//r[i][k]=true表示i行有k
bool c[10][10] = {{0}};//c[i][k]=true表示i列有k
bool p[10][10] = {{0}};//p[i][k]=true表示i宫有k
void srh(int x, int y){
if (x == 10) {//到第10行,说明前9行填完了,结束
show();
return ;
}
//否则继续递归
if (a[x][y] != 0) {//如果已经填好
if (y == 9)//直接进入下一格
srh(x + 1, 1);
else
srh(x, y + 1);
}
else {
//尝试每种填法,并接进入下一格
for (int i = 1; i <= 9; i++)//尝试1~9能不能填
if (!r[x][i] && !c[y][i] && !p[pl[x][y]][i]) {
r[x][i] = c[y][i] = p[pl[x][y]][i] = true;
a[x][y] = i;
if (y == 9)
srh(x + 1, 1);
else
srh(x, y + 1);
r[x][i] = c[y][i] = p[pl[x][y]][i] = false;
a[x][y] = 0;
}
}
}
int main()
{
for (int i = 1; i <= 9; i++)
for (int j = 1; j <= 9; j++) {
cin >> a[i][j];
r[i][a[i][j]] = true;
c[j][a[i][j]] = true;
p[pl[i][j]][a[i][j]] = true;
}
srh(1, 1);
return 0;
}
声明:如果有其他人写了差不多的,我说一下,我是原创