POJ-2676-Sudoku

来源:互联网 发布:紫金桥实时数据库 编辑:程序博客网 时间:2024/05/12 01:09
Sudoku
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 19015 Accepted: 9156 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

1103000509002109400000704000300502006060000050700803004000401000009205800804000107

Sample Output

143628579572139468986754231391542786468917352725863914237481695619275843854396127

Source

Southeastern Europe 2005



这个题就是数独,规则大家都知道:

1、同行不能有相同元素

2、同列不能有相同元素

3、同一个九宫格不能有相同元素


具体就是用3个vist数组来做标记

vist[i][x]=1,表示第i行出现过x;

vist[j][x]=1,表示第j列出现过x;

vist[i][j][x]=1,表示坐标为i,j的小方格出现过x;


具体操作见代码

#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <algorithm>using namespace std;int cnt,flag;int Map[10][10],vistrow[10][10],vistcol[10][10],vistkaui[10][10][10];struct node{int x,y;}a[100];void DFS(int x){if(x == cnt){flag = 1;return;}int I = a[x].x;int J = a[x].y;for(int i = 1; i < 10; i++){if(!vistrow[I][i] && !vistcol[J][i] && !vistkaui[I/3][J/3][i]){Map[I][J] = i;vistrow[I][i] = 1;vistcol[J][i] = 1;vistkaui[I/3][J/3][i] = 1;DFS(x+1);if(!flag){Map[I][J] = 0;vistrow[I][i] = 0;vistcol[J][i] = 0;vistkaui[I/3][J/3][i] = 0;}}}}int main(){int test;scanf("%d",&test);while(test--){memset(vistrow,0,sizeof(vistrow));memset(vistcol,0,sizeof(vistcol));memset(vistkaui,0,sizeof(vistkaui));cnt = 0;flag = 0;char str[10];for(int i = 0; i < 9; i++){scanf("%s",str);for(int j = 0; j < 9; j++){Map[i][j] = str[j]-'0';if(Map[i][j] == 0){a[cnt].x = i;a[cnt++].y = j;}else{vistrow[i][Map[i][j]] = 1;vistcol[j][Map[i][j]] = 1;vistkaui[i/3][j/3][Map[i][j]] = 1;}}}DFS(0);for(int i = 0; i < 9; i++)for(int j = 0; j < 9; j++){if(j == 8)printf("%d\n",Map[i][j]);elseprintf("%d",Map[i][j]);}}return 0;}


0 0
原创粉丝点击