Sudoku
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 13665 | Accepted: 6767 | 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
讲解:游戏都玩过,但就是基本上见过没做出来过,哈哈、、、挺有意思的代码,题意都知道,关键就是如何进行搜索,其实就是不断地进行枚举,如果满足所有的条件就跳出来;
AC代码:
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<cstring> 5 using namespace std; 6 const int N = 11; 7 int Map[N][N], flag; 8 char MAp[N][N]; 9 int check(int ans,int key) 10 { 11 int x = (key-1)/9+1; 12 int y = key-(x-1)*9; 13 for(int i=1; i<=9; i++)//行是否冲突 14 if(Map[x][i] == ans) 15 return 0; 16 for(int i=1; i<=9; i++) //列是否冲突 17 if(Map[i][y] == ans) 18 return 0; 19 if(x<=3)x = 1; //x所在小九格起点 20 if(x>3 && x<7)x=4; 21 if(x>=7) x=7; 22 if(y<=3) y = 1; //y所在小九格起点 23 if(y>3 && y<7) y=4; 24 if(y>=7) y=7; 25 for(int i=0; i<3; i++) //小的九格是否冲突 26 for(int j=0; j<3; j++) 27 if(Map[x+i][y+j] == ans) 28 return 0; 29 return 1;//以上条件都不符合,返回1; 30 } 31 int dfs(int key) 32 { 33 int x = (key-1)/9+1; 34 int y = key-(x-1)*9; 35 if(key>81) 36 { 37 flag = 1; 38 return 0; 39 } 40 if(Map[x][y]!=0)//不是0,直接跳过去 41 { 42 dfs(key+1); 43 } 44 else //否者,在这个位置枚举九个数,进行递归搜索 45 { 46 for(int k=1; k<=9; k++) 47 if(check(k,key)) 48 { 49 Map[x][y] = k; 50 dfs(key+1); 51 if(flag == 1) return 0; 52 Map[x][y] = 0; 53 } 54 } 55 return 0; 56 } 57 int main() 58 { 59 int T,i,j; 60 // freopen("in2.txt","r",stdin); 61 // freopen("out2.txt","w",stdout); 62 scanf("%d",&T); 63 while(T--) 64 { 65 memset(Map,0,sizeof(Map)); 66 for(i=1; i<=9; i++) 67 for(j=1; j<=9; j++) 68 { 69 cin>>MAp[i][j]; 70 Map[i][j] = MAp[i][j]-'0'; 71 } 72 flag = 0; 73 dfs(1); 74 for(i=1; i<=9; i++) 75 { 76 for(j=1; j<=9; j++) 77 printf("%d",Map[i][j]); 78 printf(" "); 79 } 80 } 81 return 0; 82 }