Language:
Sudoku
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12243 Accepted: 4375
Description
In the game of Sudoku, you are given a large 9 × 9 grid divided into smaller 3 × 3 subgrids. For example,
. 2 7 3 8 . . 1 .
. 1 . . . 6 7 3 5
. . . . . . . 2 9
3 . 5 6 9 2 . 8 .
. . . . . . . . .
. 6 . 1 7 4 5 . 3
6 4 . . . . . . .
9 5 1 8 . . . 7 .
. 8 . . 6 5 3 4 .
Given some of the numbers in the grid, your goal is to determine the remaining numbers such that the numbers 1 through 9 appear exactly once in (1) each of nine 3 × 3 subgrids, (2) each of the nine rows, and (3) each of the nine columns.
Input
The input test file will contain multiple cases. Each test case consists of a single line containing 81 characters, which represent the 81 squares of the Sudoku grid, given one row at a time. Each character is either a digit (from 1 to 9) or a period (used to indicate an unfilled square). You may assume that each puzzle in the input will have exactly one solution. The end-of-file is denoted by a single line containing the word “end”.
Output
For each test case, print a line representing the completed Sudoku puzzle.
Sample Input
.2738…1…1…6735…293.5692.8…6.1745.364…9518…7…8…6534.
…52…8.4…3…9…5.1…6…2…7…3…6…1…7.4…3.
end
Sample Output
527389416819426735436751829375692184194538267268174593643217958951843672782965341
416837529982465371735129468571298643293746185864351297647913852359682714128574936
思路:选取空白格子,填上合法的数字。这题时间限制为1s,而dfs的复杂度较高。必须得做些优化才能过。所以不能随意选区,空白格子。要从可填数字最少的格子开始,这样可以减少分支的数量,减少复杂度。然后判断合法数字用位运算,很方便。每行每列没个方格分别用一个9位二进制数表示。1表示该位数字可以放。三个九位二进制数做位运算配合lowbit运算就可以求出该格子的合法数字。
代码;
#include<iostream>
using namespace std;
const int N = 9;
int onescount[1<<N],bit[1<<N];//前者用于存合法数字的个数,后者用于存合法数字,用的时候直接取。
int row[N],col[N],cell[3][3];
inline int lowbit(int x){
return x&(-x);
}
inline int get(int x,int y)
{
return row[x]&col[y]&cell[x/3][y/3];
}
char str[100];
bool dfs(int cnt){
if(!cnt) return true;
int minv=10;
int x,y;
//优先选合法数字少的
for(int i=0;i<N;i++)
for(int j=0;j<N;j++){
if(str[i*9+j]=='.')
{
int t=onescount[get(i,j)];
if(minv>t){
minv=t;
x=i,y=j;}
}
}
for(int i=get(x,y);i;i-=lowbit(i)){
int t=bit[lowbit(i)];
row[x]-=1<<t;
col[y]-=1<<t;
cell[x/3][y/3]-=1<<t;
str[x*9+y]=t+'1';
if(dfs(cnt-1)) return true;
//恢复现场
row[x]+=1<<t;
col[y]+=1<<t;
cell[x/3][y/3]+=1<<t;
str[x*9+y]='.';
}
return false;
}
int main(){
for(int i=0;i<N;i++)
bit[1<<i]=i;
for(int i=0;i<1<<N;i++)
{
int s=0;
for(int j=i;j;j-=lowbit(j))
s++;
onescount[i]=s;
}
while(cin>>str&&str[0]!='e'){
for(int i=0;i<N;i++)row[i]=col[i]=(1<<N)-1;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
cell[i][j]=(1<<N)-1;
int cnt=0;
for(int i=0,k=0;i<N;i++){
for(int j=0;j<N;j++,k++)
if(str[k]!='.'){
int t=str[k]-'1';
row[i]-=1<<t;
col[j]-=1<<t;
cell[i/3][j/3]-=1<<t;
}
else cnt++;
}
dfs(cnt);
cout<<str<<endl;
}
}