闲来无事,写了一段数独游戏求解的程序,得出来的结果与答案结果竟然不一样,但是仔细检查后发现两个答案都是正确的,如下:
题目:
7 2 6 9 0 4 0 5 1
0 8 0 6 0 7 4 3 2
3 4 1 0 8 5 0 0 9
0 5 2 4 6 8 0 0 7
0 3 7 0 0 0 6 8 0
0 9 0 0 0 3 0 1 0
0 0 0 0 0 0 0 0 0
9 0 0 0 2 1 5 0 0
8 0 0 3 0 0 0 0 0
答案一:
7 2 6 9 3 4 8 5 1
5 8 9 6 1 7 4 3 2
3 4 1 2 8 5 7 6 9
1 5 2 4 6 8 3 9 7
4 3 7 1 9 2 6 8 5
6 9 8 5 7 3 2 1 4
2 1 3 7 5 6 9 4 8
9 6 4 8 2 1 5 7 3
8 7 5 3 4 9 1 2 6
答案二:
7 2 6 9 3 4 8 5 1
5 8 9 6 1 7 4 3 2
3 4 1 2 8 5 7 6 9
1 5 2 4 6 8 3 9 7
4 3 7 1 9 2 6 8 5
6 9 8 5 7 3 2 1 4
2 1 5 8 4 6 9 7 3
9 6 3 7 2 1 5 4 8
8 7 4 3 5 9 1 2 6
代码如下:
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
string base[9]={"1","2","3","4","5","6","7","8","9"};
string number[9][9];
bool ispermission(int x,int y,int mycurpos){
//第一个合法性判断 行
int i;
for(i=0;i<9;i++){
if(i==y) continue;
if(base[mycurpos]==number[x][i]){
return false;
}
}
//第二个合法性判断 列
for(i=0;i<9;i++){
if(i==x) continue;
if(base[mycurpos]==number[i][y]){
return false;
}
}
//第三个合法性判断 局部九宫格
int xx=x-x%3;
int yy=y-y%3;
int j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if((i+xx)==x&&(yy+j)==y)continue;
if(base[mycurpos]==number[i+xx][j+yy]){
return false;
}
}
}
return true;
}
void get_solution(int position[][2],int mycount){
int newcount=0;
int currentpos[mycount];
int i;
for(i=0;i<mycount;i++){
currentpos[i]=-1;
}
while(newcount<mycount){
int x=position[newcount][0];
int y=position[newcount][1];
int mycurpos=currentpos[newcount]+1;
if(mycurpos<9){
while(!ispermission(x,y,mycurpos)){
mycurpos++;
if(mycurpos==9){
break;
}
}
}
if(mycurpos==9){
currentpos[newcount]=-1;
number[x][y]="0";
newcount--;
}else{
currentpos[newcount]=mycurpos;
number[x][y]=base[mycurpos];
newcount++;
}
/* if(newcount==-1){
cout<<"无解"<<endl;
break;
}*/
}
};
int main()
{
string str;
int n=0,m=0;
int mycount=0;
while(cin>>str){
if(str=="0"){
mycount++;
}
number[n][m]=str;
m++;
if(m==9){
m=0;
n++;
}
if(n==9){
n=0;
int position[mycount][2];
int i,j,p=0;
for(i=0;i<9;i++){
for(j=0;j<9;j++){
if(number[i][j]=="0"){
position[p][0]=i;
position[p][1]=j;
p++;
}
}
}
get_solution(position,mycount);
//cout<<endl;
for(i=0;i<9;i++){
for(j=0;j<8;j++){
cout<<number[i][j]<<" ";
}
cout<<number[i][8]<<endl;
}
mycount=0;
}
}
}