Sudoku is a very popular intellectual game but with deep search (DFS), this problem can be easily solved.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace Std;
int map[9][9],vis[10][10],a[10][10],b[10][10];
int Count_num,flag; Count represents the number of 0
struct node
{
int x;
int y;
}NUM[82];
void Dfs (int k)
{
if (k==count_num)//Fill output
{
printf ("\ n");
flag=1;
for (int i=0;i<9;i++)
{
for (int j=0;j<9;j++)
printf ("%d", map[i][j]);
printf ("\ n");
}
printf ("\ n");
Return
}
for (int i=1;i<10;i++)//Select a number from 1-9 to fill
{
Vis[i/3*3+j/3][map[i][j]]=1;
if (!vis[num[k].x/3*3 + num[k].y/3][i] &&!a[num[k].x][i] &&!b[i][num[k].y])//Determine if there is no this number/column in each nine Number
{
Map[num[k].x][num[k].y]=i; Fill in this number.
vis[num[k].x/3*3+num[k].y/3][i]=1;////////
A[num[k].x][i]=1;
B[i][num[k].y]=1;
DFS (K+1);
if (flag)//Completed task return
Return
map[num[k].x][num[k].y]=0;//does not conform to this number
vis[num[k].x/3*3+num[k].y/3][i]=0;/////return to zero
a[num[k].x][i]=0; Return to zero
b[i][num[k].y]=0;
}
}
Return
}
int main ()
{
int k=1;
while (k)
{
flag=0;
cout<< "Please enter Sudoku form: \ n";
memset (vis,0,sizeof (VIS)); Two-dimensional empty array
memset (A,0,sizeof (a));
Memset (b,0,sizeof (b));
count_num=0;
flag=0;
for (int i=0;i<9;i++)
for (int j=0;j<9;j++)
{
scanf ("%d", &map[i][j]);
if (Map[i][j])
{
Vis[i/3*3+j/3][map[i][j]]=1; It's in the nine, there's this number.
A[i][map[i][j]]=1; The line has this number
B[map[i][j]][j]=1; The column has this number
}
Else
{
Num[count_num].x=i;
Num[count_num++].y=j; Note the space coordinates
}
}
cout<< "The answer is: \ n";
DFS (0);
if (!flag) cout<< "no answer!" "<<endl;
}
return 0;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Deep Search and Play Sudoku