openjudge-NOI 2.5-1700 八皇后问题

题目链接:http://noi.openjudge.cn/ch0205/1700/

题解:

  经典深搜题目……

 1 #include<cstdio>
 2 bool a[9][9];
 3 int num;
 4 void print()
 5 {
 6     printf("No. %d\n",num);
 7     for(int i=1;i<=8;i++)
 8     {
 9         for(int j=1;j<=8;j++)
10         {
11             printf("%d ",a[j][i]);
12         }
13         printf("\n");
14     }
15 }
16 int check(int x,int y)
17 {
18     int tmp1,tmp2;
19     tmp1=1;tmp2=y-x+1;
20     for(;tmp1<=x;tmp1++,tmp2++)
21     {
22         if(tmp2>=1&&tmp2<=8&&a[tmp1][tmp2]==true)return 0;
23     }
24     tmp1=1;tmp2=y+x-1;
25     for(;tmp1<=x;tmp1++,tmp2--)
26     {
27         if(tmp2>=1&&tmp2<=8&&a[tmp1][tmp2]==true)return 0;
28     }
29     tmp1=1;tmp2=y;
30     for(;tmp1<=x;tmp1++)
31     {
32         if(tmp2>=1&&tmp2<=8&&a[tmp1][tmp2]==true)return 0;
33     }
34     return 1;
35 }
36 void dfs(int dep)
37 {
38     if(dep==9)
39     {
40         num++;
41         print();
42     }
43     else
44     {
45         for(int i=1;i<=8;i++)
46         {
47             if(dep==1||check(dep,i)==1)
48             {
49                 a[dep][i]=true;
50                 dfs(dep+1);
51                 a[dep][i]=false;
52             }
53         }
54     }
55 }
56 int main()
57 {
58     dfs(1);
59     return 0;
60 }

 

posted @ 2016-10-26 12:58  xqmmcqs  阅读(522)  评论(0编辑  收藏  举报