TOJ 3287 Sudoku dfs

3287: Sudoku 

描述

 

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. 

输入

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.

输出

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.

样例输入

1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107

样例输出

143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127

数独游戏,每个格子填写1-9的数字,要求3*3的小格子里不能有重复数字,9*9的大格子里每行每列不能有重复的数字。所以要check三下,分别是行,列和3*3的小方阵。(小方阵的序号以3*(i/3)+j/3来表示)

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define inf 0x3f3f3f3f
#define LL long long
int a[20][20],flag;
int r[20][20],l[20][20],s[20][20];//r行 l列 s小方阵 
void dfs(int i,int j)
{if(i==9&&j==0)flag=1;	else{if(a[i][j]!=0){if(j<8)dfs(i,j+1);elsedfs(i+1,0);}else{for(int k=1;k<=9;k++){if(!r[i][k]&&!l[j][k]&&!s[3*(i/3)+j/3][k]){a[i][j]=k;r[i][k]=1;l[j][k]=1;s[3*(i/3)+j/3][k]=1;if(j<8)dfs(i,j+1);elsedfs(i+1,0);if(flag)return;//回溯重置 a[i][j]=0;r[i][k]=0;l[j][k]=0;s[3*(i/3)+j/3][k]=0;}}}}
}
int main()
{int t,i,j;scanf("%d",&t);while(t--){memset(r,0,sizeof r);memset(l,0,sizeof l);		memset(s,0,sizeof s);for(i=0;i<9;i++){for(j=0;j<9;j++){scanf("%1d",&a[i][j]);if(a[i][j]){r[i][a[i][j]]=1;l[j][a[i][j]]=1;s[3*(i/3)+j/3][a[i][j]]=1;}}}flag=0;dfs(0,0);for(i=0;i<9;i++){for(j=0;j<9;j++){printf("%d",a[i][j]);}printf("\n");}}
}

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部