九度 1140 题目1140:八皇后

http://ac.jobdu.com/problem.php?id=1140  DFS,深度搜索时,从第一行到第8行,用col[i]记录第i行的皇后放的位置(也就是第几列)。

View Code
 1 #include<iostream>
2 #include<cstring>
3 #include<cmath>
4 #include<algorithm>
5 #include<vector>
6 #define N 8
7 using namespace std;
8 bool mat[N+1][N+1];
9 int col[N+1];//col[i]:i行col[i]列放皇后
10 vector<string>v;//里面放皇后串
11 int num;
12 char str[10];//放一个皇后串
13 void init()
14 {
15 memset(col,-1,sizeof(col));//col[i]==-1:代表i行没放皇后
16 v.clear();
17 num=0;
18 }
19 bool ok(int i)//看第i行能不能放
20 {
21 for(int row=1;row!=i;row++)//只需要看i以前,的某行与没有放
22 {
23 if(i!=row && col[i]!=-1 && col[row]!=-1)//不是同一行 ,且i行和row行都有放皇后
24 {
25 //不在同一行和列,且不在同一对角线
26 if(col[i]==col[row] || abs(i-row)==abs(col[i]-col[row])) return false;
27 }
28 }
29 return true;
30 }
31 void dfs(int cur)
32 {
33 for(int j=1;j<=N;j++)
34 {
35 col[cur]=j;//在第cur行,的第j列放皇后,如果行,继续dfs;不行的话,第cur行放j+1列
36 str[cur-1]=j+'0';
37 if(ok(cur))
38 {
39 if(cur==N) //放了N个
40 {
41 //num++;
42 string s=str;
43 v.push_back(s);//把一个皇后串压入向量
44 }
45 else dfs(cur+1);
46 }
47 }
48 }
49 int main()
50 {
51 init();
52 dfs(1);
53 sort(v.begin(),v.end());
54 int t,i;
55 cin>>t;
56 while(t--)
57 {
58 cin>>i;
59 cout<<v[i-1]<<endl;
60 }
61 // system("pause");
62 return 0;
63 }


 

转载于:https://www.cnblogs.com/keepmoving89/archive/2012/04/06/2434772.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值