poj2676 (dfs+回溯)
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 24108 | Accepted: 11259 | Special Judge |
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
Southeastern Europe 2005 題意:數獨遊戲, 規則------->>>>> 1.每行每列都包含1到9,且數字不重復。 每個3*3的小矩陣中也包含數字1到9,數字不重復。 思路: 做標記, 3個標記,分別行,列和小矩陣, 數字1到9,用過標記,true,否則 false。 ac代碼:#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
#define Swap(a,b,t) t=a,a=b,b=t
#define Mem0(x) memset(x,0,sizeof(x))
#define Mem1(x) memset(x,-1,sizeof(x))
#define MemX(x) memset(x,0x3f,sizeof(x));
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f;
const double eps=1e-12;
const int MAX=15;
int map[MAX][MAX];
char temp[MAX];
bool row[MAX][MAX],line[MAX][MAX],rl[MAX][MAX],flag=false;
void dfs(int x,int y)
{
if (x==10){
flag=true;
return ;
}
if (map[x][y]){
if (y==9)
dfs(x+1,1);
else
dfs(x,y+1);
if (flag)
return ;
}
else{
int k=3*((x-1)/3)+(y-1)/3+1;
for (int i=1;i<10;i++){
if (!row[x][i]&&!line[y][i]&&!rl[k][i]){
map[x][y]=i;
row[x][i]=line[y][i]=rl[k][i]=true;
if (y==9)
dfs(x+1,1);
else
dfs(x,y+1);
if(flag)
return ;
map[x][y]=0;
row[x][i]=line[y][i]=rl[k][i]=false;
}
}
}
}
int main()
{
int t;
cin>>t;
while (t--){
flag=false;
memset(map,0,sizeof(map));
memset(row,false,sizeof(row));
memset(line,false,sizeof(line));
memset(rl,false,sizeof(rl));
for (int i=1;i<10;i++){
cin>>temp+1;
for (int j=1;j<10;j++){
map[i][j]=temp[j]-‘0‘;
if (map[i][j]){
int k=3*((i-1)/3)+(j-1)/3+1;
row[i][map[i][j]]=line[j][map[i][j]]=rl[k][map[i][j]]=true;
}
}
}
dfs(1,1);
for (int i=1;i<10;i++){
for (int j=1;j<10;j++){
printf("%d",map[i][j]);
}
printf("\n");
}
}
return 0;
}
poj2676 (dfs+回溯)