八皇后问题

八皇后问题,是回溯算法的典型例题。该问题是十九世纪著名的数学家高斯1850年提出:在8X8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。 高斯认为有76种方案。1854年在柏林的象棋杂志上不同的作者发表了40种不同的解,后来有人用图论的方法解出92种结果。

具体思路可参考:

http://jpkc.onlinesjtu.com/CourseShare/datastructure/FlashInteractivePage/exp7.htm

思路:
nQueens(int row) { if(row == n) { //满足条件,输出 } for(i = 0;i < n;i++) { if(IsSafe) //若位置合适 { //下一个 } } }

代码如下:

 1 #include <iostream>
 2 using namespace std;
 3 int n,num=1;
 4 int qu[100];
 5 
 6 void Print()
 7 {
 8     cout<<num++<<":    ";
 9     int i;
10     for(i = 0;i < n;i++)
11     {
12         cout<<qu[i]<<" ";
13     }    
14     cout<<endl;
15 }
16 
17 bool IsSafe(int row,int col)
18 {
19     for(int i=0;i<row;i++)
20     {
21         if(qu[i] == col)
22         {        
23             return false;
24         }
25         if((qu[i]+i) == (row+col))
26         {
27             return false;
28         }
29          if((qu[i]-i) == (col-row))
30         {
31             return false;
32         }
33     }
34     qu[row]=col;
35     return true;
36 }
37 
38 void nQueens(int row)
39 {
40     if(row == n)        
41     {
42         Print();
43         return ;
44     }
45     int i;
46     for(i = 0;i < n;i++)
47     {
48         if(IsSafe(row,i))
49         {
50             nQueens(row+1);
51         }
52     }
53 }
54 int main()
55 {
56     cin>>n;
57     nQueens(0);
58     return 0;
59 }

输入:

4

输出:

1: 1 3 0 2
2: 2 0 3 1

以第一种方法为例,有以下排列:

     
     
     
     
原文地址:https://www.cnblogs.com/boyiliushui/p/5135543.html