算法思想:利用行号固定,列号全排列解决;这样没有i == j 和board[i] == board[j]的冲突;
只要检测(j-i) == (size_t)abs(board[i]-board[j])就说明冲突!
1 #include <cmath>
2 #include <iostream>
3 #include <vector>
4 #include <algorithm>
5
6 using namespace std;
7 const int MAX = 8;
8
9 vector<int> board(MAX);
10
11 void show_result()
12 {
13 for(size_t i = 0; i < board.size(); i++)
14 cout<<"("<<i<<","<<board[i]<<")";
15 cout<<endl;
16 }
17
18 int check_cross()
19 {
20 for(size_t i = 0; i < board.size()-1; i++)
21 {
22 for(size_t j = i+1; j < board.size(); j++)
23 {
24 if((j-i) == (size_t)abs(board[i]-board[j]))
25 return 1;
26 }
27 }
28 return 0;
29 }
30
31 void put_chess()
32 {
33 while(next_permutation(board.begin(), board.end()))
34 {
35 if(!check_cross())
36 {
37 show_result();
38 }
39 }
40 }
41
42 int main()
43 {
44 for(size_t i =0; i < board.size(); i++)
45 board[i] = i;
46 put_chess();
47 return 0;
48 }