博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
八行代码解决八皇后问题(c++)
阅读量:6967 次
发布时间:2019-06-27

本文共 3031 字,大约阅读时间需要 10 分钟。

  说的有点夸装,实际上并不只是巴航代码,加上前面的变量声明之类的一共有40多行的样子吧,好像是

在知乎上看到的,现在有时间再把它写下来:
  其中用到了一些c++11特性,例如lambda 以及给予范围的 for循环。
  其他的没什么好说的,看代码,上面也有注释的。

1 #include 
2 #include
3 #include
4 #include
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
border(n);18 for (int i = 0; i < n; ++i)19 border[i] = i + 1; //这一步就决定了每一行的上下左右都不会有其他的皇后20 vector
afterAdd(8);21 vector
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
afterAddSet(afterAdd.begin(), afterAdd.end());28 set
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 3 6 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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种方式,由于是枚举了所有的可能情况,所以用时稍微有一点长。

转载于:https://www.cnblogs.com/-wang-cheng/p/4854484.html

你可能感兴趣的文章
源码包编译安装之--实战
查看>>
powershell 批量查询导出 组织内OU
查看>>
我的友情链接
查看>>
昨日终于考完路考了
查看>>
转:解决 linux下编译make文件报错“/bin/bash^M: 坏的解释器:没有那个文件或目录...
查看>>
Discuz 7.2坑爹集锦-PHP篇 update 20120525
查看>>
IDEA 2016.3 导入项目
查看>>
spring4+hibernate4+struts2注解,class找不到bean
查看>>
java中synchronized和Lock的区别
查看>>
python练习-数值比较
查看>>
win7,centos双系统无法启动centos,跳到grub命令行
查看>>
我的友情链接
查看>>
堆和栈的区别
查看>>
MongoDB基本命令用法
查看>>
MongoDB基本命令用法
查看>>
Docker的四种网络方式
查看>>
【Qt笔记】可视化显示数据库数据
查看>>
Spring Boot 2.0正式发布,升还是不升呢?
查看>>
Android四大组件Activity,及Intent的简单用法
查看>>
线程同步控制
查看>>