解数独..暴搜即可
一开始傻逼的以为没必要把格子还原为0,wa了半天还坚信这不用还原...长记性了。。
还有这题正搜和反搜时间差好多,正搜要400ms反搜只需16ms....
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char tpic[15][15];
int pic[15][15], book_row[10][10], book_col[10][10], book_cel[5][5][10];
bool ok;
void dfs(int x, int y)
{
if(ok) return ;
if(y == 9) x++, y = 0;
if(x == 9) { ok = 1; return ; }
if(pic[x][y]) dfs(x, y+1);
else
{
for(int i = 1; i <= 9; i++)
{
if(!book_row[x][i] && !book_col[y][i] && !book_cel[x/3][y/3][i])
{
pic[x][y] = i;
book_row[x][i] = book_col[y][i] = book_cel[x/3][y/3][i] = 1;
dfs(x, y+1);
if(ok) return ;
pic[x][y] = book_row[x][i] = book_col[y][i] = book_cel[x/3][y/3][i] = 0;
}
}
}
}
int main(void)
{
//freopen("in.txt", "r", stdin);
int t;
cin >> t;
while(t--)
{
ok = 0;
memset(book_row, 0, sizeof(book_row));
memset(book_col, 0, sizeof(book_col));
memset(book_cel, 0, sizeof(book_cel));
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{
scanf(" %c", &tpic[i][j]);
int val = tpic[i][j]-48;
pic[i][j] = val;
if(val) book_row[i][val] = book_col[j][val] = book_cel[i/3][j/3][val] = 1;
}
dfs(0, 0);
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{
printf("%d", pic[i][j]);
if(j == 8) printf("\n");
}
}
return 0;
}
Sudoku
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 18750 | Accepted: 9044 | 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