- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <cmath>
- using namespace std;
- const int MAX = 8;
- vector<int> board(MAX);
- void show_result()
- {
- for(size_t i = 0;i < board.size();++i) {
- cout << "(" << i << "," << board[i] << ")";
- }
- cout << endl;
- }
- int check_cross()
- {
- //核心就是检测有没有交叉
- //等于是board存储的是行或者列的一个坐标排列
- //等于生成各种8个棋子的坐标排列进行判断
- //这里i和j都是不同的
- //首先board的排列不会出现同一行同一个列的情况
- //然后是i和j不会出现相同的情况
- //这样就避免去判断两个棋子是不是排列到同一行或者
- //同一列的情况
- for(size_t i = 0;i < board.size() - 1;++i) {
- for(size_t j = i + 1;j < board.size();j++) {
- if((j - i) == (size_t)abs(board[i] - board[j])) {
- return 1;
- }
- }
- }
- return 0;
- }
- void put_chess()
- {
- while(next_permutation(board.begin(),board.end())) {
- if(!check_cross()) {
- show_result();
- }
- }
- }
- int
- main(int argc,char *argv[])
- {
- for(size_t i = 0;i < board.size();++i) {
- board[i] = i;
- }
- put_chess();
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/0412201411175.html
来源: http://www.codesnippet.cn/detail/0412201411175.html