Sudoku
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 11575 | Accepted: 5748 | 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 题目链接:
1 #include2 #include 3 4 bool bResult; 5 const int MAX_N = 10; 6 char sudoku[MAX_N][MAX_N]; 7 8 void printResult() 9 {10 for(int i = 0; i < 9; i++)11 printf("%s\n", sudoku[i]);12 }13 14 bool JudgeStatue(int curCount, int num)15 {16 int row = curCount / 9;17 int col = curCount % 9;18 for(int j = 0; j < 9; j++) //判断同一行是否有相同的数字19 if(sudoku[row][j] == '0' + num)20 return false;21 for(int i = 0; i < 9; i++) //判断同一列是否有相同的数字22 if(sudoku[i][col] == '0' + num)23 return false;24 25 //判断在一个小的九宫格里是否有相同的数字26 for(int i = row-row%3; i < row-row%3 + 3; i++)27 for(int j = col-col%3; j < col-col%3 + 3; j++)28 if(sudoku[i][j] == '0' + num)29 return false;30 return true;31 }32 33 void dfs(int curCount) //curCount代表当前下标34 {35 if(curCount == -1)36 {37 bResult = true;38 printResult();39 return ;40 }41 if(bResult)return ;42 43 for(int num = 1; num <= 9; num++)44 {45 if(sudoku[curCount/9][curCount%9]-'0' != 0)46 {47 curCount--;48 if(curCount == -1)49 {50 bResult = true;51 printResult();52 return ;53 }54 num = 0;55 continue;56 }57 58 if(JudgeStatue(curCount, num))59 {60 sudoku[curCount/9][curCount%9] = num + '0';61 dfs(curCount - 1);62 sudoku[curCount/9][curCount%9] = '0';63 }64 }65 }66 67 int main()68 {69 int nCase;70 71 scanf("%d", &nCase);72 getchar();73 while(nCase--)74 {75 bResult = false;76 memset(sudoku, 0, sizeof(sudoku));77 for(int i = 0; i < 9; i++)78 {79 gets(sudoku[i]);80 }81 82 dfs(80); //从最后一个数字开始搜索83 }84 return 0;85 }
题目总结:经典的DFS题目,可以从前往后搜索,也可以倒着搜索,从前往后搜索1704MS,倒着搜索16MS,
应该是测试数据的原因,导致有这么大的差别。