POJ2676

Problem

分析:我们可以这样考虑,如果一个数在位置(x,y)出现过了,则在第x行,第y列,以及(x,y)所对应的3*3所对应的方格中都不会出现,由此我们用三个数组标记这三个变量,然后在对于没有填数的位置进行dfs即可

 1 #include "iostream"
 2 #include "cstdio"
 3 #include "cstring"
 4 #include "vector"
 5 using namespace std;
 6 const int maxn=15;
 7 
 8 int row[maxn][maxn]; //在第i行填入了num
 9 int col[maxn][maxn]; //在第j列填入了num
10 int pos[maxn][maxn]; //在(i,j)所对应的方块中填入了num
11 int res[maxn][maxn]; //记录最终值
12 typedef struct{
13     int r,c;
14 }point;
15 vector<point> vis; //记录没有填数的位置
16 
17 int getpos(int i,int j){  //获取(i,j)所在方块号
18     int ii=i/3;
19     int jj=j/3;
20     return ii*3+jj;
21 }
22 
23 void setAll(int i,int j,int num,int f){   //在(i,j)填入num
24     row[i][num]=f;
25     col[j][num]=f;
26     pos[getpos(i,j)][num]=f;
27 }
28 
29 bool judge(int i,int j,int num){    //判断(i,j)位置能不能填数
30     if((!row[i][num])&&(!col[j][num])&&(!pos[getpos(i,j)][num]))
31         return true;
32     return false;
33 }
34 
35 bool dfs(int n){  //填数
36     if(n<0)
37         return true;
38     for(int i=1;i<=9;i++){
39         int x=vis[n].r,y=vis[n].c;
40         if(judge(x,y,i)){
41             setAll(x,y,i,1);
42             res[x][y]=i;
43             if(dfs(n-1))
44                 return true;
45             setAll(x,y,i,0);
46         }
47     }
48     return false;
49 }
50 
51 int main()
52 {
53     int T;
54     cin>>T;
55     while(T--){
56         memset(row,0,sizeof(row));
57         memset(col,0,sizeof(col));
58         memset(pos,0,sizeof(pos));
59         memset(res,0,sizeof(res));
60         vis.clear();
61         for(int i=0;i<9;i++){
62             for(int j=0;j<9;j++){
63                 char ch;
64                 cin>>ch;
65                 int cnt=ch-'0';
66                 if(cnt){
67                     res[i][j]=cnt;
68                     setAll(i,j,cnt,1);
69                 }else{
70                     point a;
71                     a.r=i,a.c=j;
72                     vis.push_back(a);
73                 }
74             }
75         }
76         if(dfs(vis.size()-1)){
77             for(int i=0;i<9;i++){
78                 for(int j=0;j<9;j++){
79                     printf("%d",res[i][j]);
80                 }
81                 printf("
");
82             }
83         }
84     }
85     return 0;
86 }
View Code
原文地址:https://www.cnblogs.com/wolf940509/p/6567388.html