POJ2676--Sudoku

来源:互联网 发布:绿盾防泄密软件 编辑:程序博客网 时间:2024/05/01 06:00

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

1103000509002109400000704000300502006060000050700803004000401000009205800804000107

Sample Output

143628579572139468986754231391542786468917352725863914237481695619275843854396127
//看完题目就一阵狂撸。。结果没有看到每个子网格也要只能出现一次。。。此题会做八皇后的话问题不大。#include <iostream>#include <cstdio>#include <cstring>#include <string>using namespace std;int map[10][10];bool vis[10][10],val[10][10],vzi[10][10];bool flag;void dfs(int r,int c){if(map[r][c])//如果这个数已经是给好的{//那么应该直接搜索下一个数if(c<9)dfs(r,c+1);else if(r<9)dfs(r+1,1);else {flag=true;return;}}else//如果这个数不是系统给好的{for(int i=1;i<=9;i++){if(!vis[r][i]&&!val[c][i]&&!vzi[((c+2)/3-1)*3+(r+2)/3][i]){vis[r][i]=val[c][i]=vzi[((c+2)/3-1)*3+(r+2)/3][i]=1;map[r][c]=i;if(c<9){dfs(r,c+1);if(flag)return;vis[r][i]=val[c][i]=vzi[((c+2)/3-1)*3+(r+2)/3][i]=0;map[r][c]=0;}else if(r<9){dfs(r+1,1);if(flag)return;vis[r][i]=val[c][i]=vzi[((c+2)/3-1)*3+(r+2)/3][i]=0;map[r][c]=0;}else {flag=true;return;}}}}}int main(){int t;scanf("%d",&t);getchar();while(t--){flag=false;memset(vis,0,sizeof(vis));memset(val,0,sizeof(val));memset(vzi,0,sizeof(vzi));for(int i=1;i<=9;i++){for(int j=1;j<=9;j++){map[i][j]=getchar()-'0';if(map[i][j]){int fuck=map[i][j];vis[i][fuck]=1;val[j][fuck]=1;vzi[((j+2)/3-1)*3+(i+2)/3][fuck]=1;}}getchar();}dfs(1,1);for(int i=1;i<=9;i++){for(int j=1;j<=9;j++){printf("%d",map[i][j]);}printf("\n");}}return 0;}