博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
N-Queens II
阅读量:4458 次
发布时间:2019-06-08

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

Q:

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

A: 用N-Queens的方法,当n=12时,会超时。

下述方法,把可以放皇后的位置,直接计算出来,不需要每次遍历并判断。

void queens(int row,int ld,int rd,int upper,int& cnt){    if(row==upper)        cnt++;    else    {        int pos = upper&(~(row|ld|rd));  //pos中等于1的位置,表示可以放皇后的位置        while(pos) //pos==0,表示不可以放皇后了        {            int p = pos&(-pos);  // pos&(-pos) = pos&(~pos+1),表示取出取出最右边的那个1            pos = pos - p;            queens(row+p,(ld+p)<<1,(rd+p)>>1,upper,cnt);        }    }}int totalNQueens(int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function    int cnt = 0;    if(n>0)    {        int upper = (1<

 

转载于:https://www.cnblogs.com/summer-zhou/p/3265073.html

你可能感兴趣的文章
Python基础综合练习
查看>>
JVM参数配置 java内存区域
查看>>
《将博客搬至CSDN》
查看>>
python 防死锁机制
查看>>
python--使用递归优雅实现列表相加和进制转换
查看>>
一般邮件的针对SPF的TXT记录应该如何写?
查看>>
node.js操作mysql数据库之增删改查
查看>>
JVM检测&工具
查看>>
【语言处理与Python】8.5依存关系和依存文法\8.6文法开发
查看>>
(7)第3章的开始
查看>>
[ArcGIS+Win7][转]安装ArcGIS后打开"打开或关闭 Windows 功能"一片空白解决方案
查看>>
android用欢迎界面加载运行环境
查看>>
MySql实现远程访问配置
查看>>
eclipse 集成Maven(转自:http://blog.csdn.net/wode_dream/article/details/38052639)
查看>>
LeetCode - Combination Sum
查看>>
屏幕旋转,ViewController触发事件
查看>>
响应重定向和请求转发
查看>>
java例程练习(File类)
查看>>
Linux && 与 ||
查看>>
Python configparser模块
查看>>