hdu 1426(九宫格)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1426

思路:dfs搜索(回溯),有个小技巧,就是行、列的表示,具体见代码。。

View Code
 1 #include<iostream>
 2 using namespace std;
 3 bool flag;
 4 int map[10][10];
 5 int row[10][10];
 6 int line[10][10];
 7 struct Matrix{
 8     bool num[10];
 9 }mat[4][4];//小的九宫格
10 
11 
12 void dfs(int _count){
13     //9*9个数
14     if(_count>81){
15         flag=true;
16         for(int i=1;i<=9;i++){
17             for(int j=1;j<9;j++){
18                 printf("%d ",map[i][j]);
19             }
20             printf("%d\n",map[i][9]);
21         }
22         return ;
23     }
24     if(!flag){
25         int Row=(_count-1)/9+1;//
26         int Line=(_count-1)%9+1;//27         //此处要填数字
28         if(map[Row][Line]==0){
29             for(int i=1;i<=9;i++){
30                 if(!row[Row][i]&&!line[Line][i]&&!mat[(Row-1)/3+1][(Line-1)/3+1].num[i]){
31                     row[Row][i]=true;
32                     line[Line][i]=true;
33                     mat[(Row-1)/3+1][(Line-1)/3+1].num[i]=true;
34                     map[Row][Line]=i;
35 
36                     dfs(_count+1);
37                     //要恢复现场
38                     map[Row][Line]=0;
39                     row[Row][i]=false;
40                     line[Line][i]=false;
41                     mat[(Row-1)/3+1][(Line-1)/3+1].num[i]=false;
42                 }
43             }
44         }else 
45             dfs(_count+1);
46     }
47 }
48 
49 
50 int main(){
51     char str[4];
52     int _case=0;
53     while(~scanf("%s",str)){
54         flag=false;
55         memset(row,false,sizeof(row));
56         memset(line,false,sizeof(line));
57         memset(mat,false,sizeof(mat));
58         if(_case++)printf("\n");
59         if(str[0]!='?'){
60             map[1][1]=str[0]-'0';
61             mat[1][1].num[str[0]-'0']=true;
62             row[1][str[0]-'0']=true;
63             line[1][str[0]-'0']=true;
64         }else 
65             map[1][1]=0;
66         for(int i=2;i<=9;i++){
67             scanf("%s",str);
68             if(str[0]!='?'){
69                 map[1][i]=str[0]-'0';
70                 mat[1][(i-1)/3+1].num[str[0]-'0']=true;
71                 row[1][str[0]-'0']=true;
72                 line[i][str[0]-'0']=true;
73             }else
74                 map[1][i]=0;
75         }
76         for(int i=2;i<=9;i++){
77             for(int j=1;j<=9;j++){
78                 scanf("%s",str);
79                 if(str[0]!='?'){
80                     map[i][j]=str[0]-'0';
81                     mat[(i-1)/3+1][(j-1)/3+1].num[str[0]-'0']=true;
82                     row[i][str[0]-'0']=true;
83                     line[j][str[0]-'0']=true;
84                 }else 
85                     map[i][j]=0;
86             }
87         }
88         dfs(1);
89     }
90     return 0;
91 }
92         
原文地址:https://www.cnblogs.com/wally/p/3001973.html