八行代码解决八皇后问题(c++)

  说的有点夸装,实际上并不只是巴航代码,加上前面的变量声明之类的一共有40多行的样子吧,好像是
在知乎上看到的,现在有时间再把它写下来:
  其中用到了一些c++11特性,例如lambda 以及给予范围的 for循环。
  其他的没什么好说的,看代码,上面也有注释的。

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 #include <set>
 5 using namespace std;
 6 void eightQueen(int n);
 7 int main()
 8 {
 9     eightQueen(8);
10     system("pause");
11     return 0;
12 }
13 
14 void eightQueen(int n)
15 {
16     int count = 0;
17     vector<int> border(n);
18     for (int i = 0; i < n; ++i)
19         border[i] = i + 1;    //这一步就决定了每一行的上下左右都不会有其他的皇后
20     vector<int> afterAdd(8);
21     vector<int> afterSub(8);
22     for(;;){
23         transform(border.begin(), border.end(), afterAdd.begin(), 
24             [](int i)->int{static int index = 1; i += index; index++; return i; });
25         transform(border.begin(), border.end(), afterSub.begin(), 
26             [](int i)->int{static int index = 1; i -= index; index++; return i; });
27         set<int> afterAddSet(afterAdd.begin(), afterAdd.end());
28         set<int> afterSubSet(afterSub.begin(), afterSub.end());
29         if (afterAddSet.size() == 8 && afterSubSet.size() == 8){    //如果斜对角线上都没有元素话
30             ++count;
31             for (auto c : border)
32                 cout << c << ' ';
33             cout << endl;
34         }
35         if (!next_permutation(border.begin(), border.end())){
36             cout << "Total : " << count << endl;
37             break;
38         }
39     }
40 }

嗯大概就是这样,下面是结果:

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 8 2 4 6 
3 5 2 8 1 7 4 6 
3 5 2 8 6 4 7 1 
3 5 7 1 4 2 8 6 
3 5 8 4 1 7 2 6 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 7 1 3 5 2 8 
6 4 7 1 8 2 5 3 
6 8 2 4 1 7 5 3 
7 1 3 8 6 4 2 5 
7 2 4 1 8 5 3 6 
7 2 6 3 1 4 8 5 
7 3 1 6 8 5 2 4 
7 3 8 2 5 1 6 4 
7 4 2 5 8 1 3 6 
7 4 2 8 6 1 3 5 
7 5 3 1 6 8 2 4 
8 2 4 1 7 5 3 6 
8 2 5 3 1 7 4 6 
8 3 1 6 2 5 7 4 
8 4 1 3 6 2 7 5 
Total : 92

一共有92种方式,由于是枚举了所有的可能情况,所以用时稍微有一点长。

posted @ 2015-10-04 13:44  eversliver  阅读(6109)  评论(0编辑  收藏  举报