POJ 2676-Sudoku(DFS)

来源:互联网 发布:一个5皇冠淘宝店多少钱 编辑:程序博客网 时间:2024/05/16 10:09
Sudoku
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 14120 Accepted: 6976 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
深搜。。
题意:就是传统的数独游戏。。找出一种方案即可。。有spj
对 行,列,以及9个3*3的方块哈希。。然后暴力深搜就行了。。实践证明倒搜比较快
#include <algorithm>#include <iostream>#include <cstring>#include <cstdlib>#include <string>#include <cctype>#include <vector>#include <cstdio>#include <cmath>#include <queue>#include <stack>#include <map>#include <set>#define ll long long#define maxn 360#define pp pair<int,int>#define INF 0x3f3f3f3f#define max(x,y) ( ((x) > (y)) ? (x) : (y) )#define min(x,y) ( ((x) > (y)) ? (y) : (x) )using namespace std;char ma[11][11];bool row[11][11],col[11][11],mar[11][11],ok;int change(int x,int y){if(x>=1&&x<=3) return y%3==0?y/3:y/3+1;else if(x>=4&&x<=6) return 3+(y%3==0?y/3:y/3+1);else return 6+(y%3==0?y/3:y/3+1);}void dfs(int num){if(ok) return ;if(num==0){for(int i=1;i<=9;i++){for(int j=1;j<=9;j++)putchar(ma[i][j]);puts("");}ok=1;return ;}int x=num%9==0?num/9:num/9+1;int y=num%9==0?9:num%9;if(ma[x][y]-'0')dfs(num-1);else{for(int i=1;i<=9;i++){if(!row[x][i]&&!col[y][i]&&!mar[change(x,y)][i]){ma[x][y]=i+'0';row[x][i]=1;col[y][i]=1;mar[change(x,y)][i]=1;dfs(num-1);ma[x][y]='0';row[x][i]=0;col[y][i]=0;mar[change(x,y)][i]=0;}}}}int main(){int T;scanf("%d",&T);while(T--){memset(row,0,sizeof(row));memset(col,0,sizeof(col));memset(mar,0,sizeof(mar));for(int i=1;i<=9;i++)scanf("%s",ma[i]+1);for(int i=1;i<=9;i++)for(int j=1;j<=9;j++)if(ma[i][j]-'0'){row[i][ma[i][j]-'0']=1;col[j][ma[i][j]-'0']=1;mar[change(i,j)][ma[i][j]-'0']=1;}ok=0;dfs(81);}return 0;}
1 0
原创粉丝点击