Sudoku
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 8 Accepted Submission(s) : 8
Special Judge
Problem Description
Sudoku is a very simple task. A square table with 9 rows and 9 columns is divided to 9 smaller squares 3x3 as shown on the Figure. In some of the cells are written decimal digits from 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits from 1 to 9, one digit per cell, in such way that in each row, in each column and in each marked 3x3 subsquare, all the digits from 1 to 9 to appear. Write a program to solve a given Sudoku-task.
Input
The input data will start with the number of the test cases. For each test case, 9 lines follow, corresponding to the rows of the table. On each line a string of exactly 9 decimal digits is given, corresponding to the cells in this line. If a cell is empty it is represented by 0.
Output
For each test case your program should print the solution in the same format as the input data. The empty cells have to be filled according to the rules. If solutions is not unique, then the program may print any one of them.
Sample Input
1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107
Sample Output
143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127
Source
PKU
一道DFS题,虽然过了但耗时都在几百ms,我写了3次,前两次耗时都在7、8百ms,最后一次500ms
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int Sudoku[9][9];
int Count,c,vacant[81][2];
bool ro[9][10],co[9][10],sq[3][3][10]; //分别标记每行、每列、每个3*3方格各个数字是否出现过 void DFS(int i)
{
if(c==Count)
return; int k;
for(k=1;k<10;k++)
{
if(!ro[vacant[i][0]][k]&&!co[vacant[i][1]][k]&&!sq[vacant[i][0]/3][vacant[i][1]/3][k])//如果没出现过
{
Sudoku[vacant[i][0]][vacant[i][1]]=k;
c++;
ro[vacant[i][0]][k]=true;
co[vacant[i][1]][k]=true;
sq[vacant[i][0]/3][vacant[i][1]/3][k]=true;
DFS(i+1);
if(c==Count)
return;
Sudoku[vacant[i][0]][vacant[i][1]]=0;
c--;
ro[vacant[i][0]][k]=false;
co[vacant[i][1]][k]=false;
sq[vacant[i][0]/3][vacant[i][1]/3][k]=false;
}
}
return;
} int main()
{
int T;
cin>>T;
while(T--)
{
int i,j;
Count=0;
c=0;
string temp[9];
memset(ro,false,sizeof(ro));
memset(co,false,sizeof(co));
memset(sq,false,sizeof(sq));
memset(vacant,0,sizeof(vacant));
for(i=0;i<9;i++)
cin>>temp[i];
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
Sudoku[i][j]=temp[i][j]-'0';
ro[i][Sudoku[i][j]]=true;
co[j][Sudoku[i][j]]=true;
sq[i/3][j/3][Sudoku[i][j]]=true;
if(Sudoku[i][j]==0)
{
vacant[Count][0]=i; //将需要填的空格位置保存
vacant[Count][1]=j;
Count++; //计算空格个数
}
}
}
DFS(0);
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
cout<<Sudoku[i][j];
cout<<endl;
}
}
}