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0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
No. 9
0 0 0 0 1 0 0 0
1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 0
...
1、递归求解
1 #include
2 using namespace std;
3
4 bool vis[3][20];//记忆数组判断列,主对角线,副对角线是否被占
5 int ans=0,num=1;
6 int p=0,pos[8];
7
8 void dfs(int cur);
9 void print();
10
11 int main()
12 {
13 dfs(1);//初始化cur为0,即从第一行开始
14 return 0;
15 }
16
17 void dfs(int cur)
18 {
19 if(cur>8)//如果当前行数超过8(表明八个皇后已经放好)则结果加一,返回继续递归
20 {
21 ans++;
22 print();
23 return;
24 }
25 //vis[0][i]判断列,vis[i][cur-i+8]判断主对角线,vis[2][cur+i]判断副对角线
26 for(int i=1;i<=8;i++)
27 if(!vis[0][i]&&!vis[1][cur-i+8]&&!vis[2][cur+i])
28 {
29 pos[p++]=i;
30 vis[0][i]=vis[1][cur-i+8]=vis[2][cur+i]=true;
31 dfs(cur+1);//深度搜索
32 vis[0][i]=vis[1][cur-i+8]=vis[2][cur+i]=false;
33 p--;
34 }
35 }
36
37 void print()
38 {
39 int i,j;
40 cout<<"No. "<
41 for(i=0;i<8;i++)
42 {
43 for(j=0;j<8;j++)
44 if(i==pos[j]-1)
45 cout<<"1 ";
46 else
47 cout<<"0 ";
48 cout<
49 }
50 /*for(i=0;i<8;i++)
51 cout<
52 cout<*/
53 }
2、直接交表
1 #include
2 int pos[736]={1,5,8,6,3,7,2,4,1,6,8,3,7,4,2,5,1,7,4,6,8,2,5,3,1,7,5,8,2,4,6,3,2,4,6,8,3,1,7,5,2,5,7,1,3,8,6,4,2,5,7,4,1,8,6,3,2,6,1,7,4,8,3,5,2,6,8,3,1,4,7,5,2,7,3,6,8,5,1,4,2,7,5,8,1,4,6,3,2,8,6,1,3,5,7,4,3,1,7,5,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