hdu5547 dfs

来源:互联网 发布:人工智能东南大学 编辑:程序博客网 时间:2024/06/05 15:50

Sudoku

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 646    Accepted Submission(s): 238


Problem Description
Yi Sima was one of the best counselors of Cao Cao. He likes to play a funny game himself. It looks like the modern Sudoku, but smaller.

Actually, Yi Sima was playing it different. First of all, he tried to generate a 4×4 board with every row contains 1 to 4, every column contains 1 to 4. Also he made sure that if we cut the board into four2×2 pieces, every piece contains 1 to 4.

Then, he removed several numbers from the board and gave it to another guy to recover it. As other counselors are not as smart as Yi Sima, Yi Sima always made sure that the board only has one way to recover.

Actually, you are seeing this because you've passed through to the Three-Kingdom Age. You can recover the board to make Yi Sima happy and be promoted. Go and do it!!!
 

Input
The first line of the input gives the number of test cases,T(1T100).T test cases follow. Each test case starts with an empty line followed by 4 lines. Each line consist of 4 characters. Each character represents the number in the corresponding cell (one of '1', '2', '3', '4'). '*' represents that number was removed by Yi Sima.

It's guaranteed that there will be exactly one way to recover the board.
 

Output
For each test case, output one line containing Case #x:, where x is the test case number (starting from 1). Then output 4 lines with 4 characters each. indicate the recovered board.
 

Sample Input
3****234141233214*243*312*421*134*41***3*2*414*2*
 

Sample Output
Case #1:1432234141233214Case #2:1243431234212134Case #3:3412123423414123
 

思路:
dfs
每个为‘*’的地方枚举1-4的4种可能性。

#include<cstdio>#include<cstring>const int N=10;char map[N][N];int line[N][N];int row[N][N];int sqr[N][N];int b[N][N];int flag=0;void init(){memset(line,0,sizeof(line));memset(row,0,sizeof(row));memset(sqr,0,sizeof(sqr));for(int i=1;i<=4;i++)for(int j=1;j<=4;j++){if(i<=2&&j<=2)b[i][j]=1;else if(i>=3&&j>=3)b[i][j]=4;else if(i>=3) b[i][j]=3;else if(j>=3) b[i][j]=2;}}void dfs(int num){if(num==17) {for(int i=1;i<=4;i++)printf("%s\n",map[i]+1);return ;}int x=(num-1)/4+1,y=num%4==0?4:num%4;if(map[x][y]!='*') dfs(num+1);else{for(int i=1;i<=4;i++){if(!line[x][i]&&!row[y][i]&&!sqr[b[x][y]][i]){map[x][y]=i+'0';line[x][i]=1;row[y][i]=1;sqr[b[x][y]][i]=1;dfs(num+1);map[x][y]='*';line[x][i]=0;row[y][i]=0;sqr[b[x][y]][i]=0;}}}}int main(){int T;scanf("%d",&T);for(int ca=1;ca<=T;ca++){init();for(int i=1;i<=4;i++){scanf(" %s",map[i]+1);for(int j=1;j<=4;j++)if(map[i][j]!='*'){int t=map[i][j]-'0';line[i][t]=1;row[j][t]=1;sqr[b[i][j]][t]=1;}}printf("Case #%d:\n",ca);dfs(0);}return 0;}



0 0
原创粉丝点击