八行代碼解決八皇后問題(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 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5 7 1 3 
6 4 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種方式,由於是枚舉了所有的可能情況,所以用時稍微有一點長。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM