Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 15698 | Accepted: 7678 | Special Judge |
Description
Input
Output
Sample Input
1 103000509 002109400 000704000 300502006 060000050 700803004 000401000 009205800 804000107
Sample Output
143628579 572139468 986754231 391542786 468917352 725863914 237481695 619275843 854396127
Source
#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> #include<vector> using namespace std; char map[15][15]; int rownum[15][15],colnum[15][15],blocknum[15][15]; //当前行、当前列、当前小块放置数字的标记。 struct pos{ int r,c; pos(int rr,int cc):r(rr),c(cc){ } }; vector<pos>blankpos; int getblocknum(int r,int c) //获取当前数字所在小块的位置 { int rr=r%3==0?r/3:(r/3+1); int cc=c%3==0?c/3:(c/3+1); return rr*3+cc; } void setflags(int i,int j,int num,int f) { rownum[i][num]=f; colnum[j][num]=f; blocknum[getblocknum(i,j)][num]=f; } bool isOk(int i,int j,int num) //判断数字是否可行 { return !rownum[i][num]&&!colnum[j][num]&&!blocknum[getblocknum(i,j)][num]; } bool dfs(int n) { if(n<0)return true; int i; int r=blankpos[n].r; int c=blankpos[n].c; for(i=1;i<=9;i++) { if(isOk(r,c,i)){ map[r][c]=i; setflags(r,c,i,1); if(dfs(n-1))return true; setflags(r,c,i,0); } } return false; } int main() { int T,i,j,k; scanf("%d",&T); while(T--) { memset(rownum,0,sizeof(rownum)); memset(colnum,0,sizeof(colnum)); memset(blocknum,0,sizeof(blocknum)); blankpos.clear(); for(i=1;i<=9;i++) for(j=1;j<=9;j++) { cin>>map[i][j]; map[i][j]=map[i][j]-'0'; if(map[i][j])setflags(i,j,map[i][j],1); else blankpos.push_back(pos(i,j)); //把空的位置放入数组 } if(dfs(blankpos.size()-1)){ for(i=1;i<=9;i++) { for(j=1;j<=9;j++) cout<<char(map[i][j]+'0'); cout<<endl; } } } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/aaaaacmer/article/details/47018699