LeetCode 笔记系列 14 N-Queen II [思考的深度问题]
题目: Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

就是让你输出N皇后问题的解法数目。
直接求解,每次还记录整个棋盘位置那种方法就不说了,必须超时。
有一个牛逼大了的超级无敌帅的位移动解法。我们暂且不表。看看我当时想的一个解法。
首先,对于皇后的那个递归方法,我有三个变量分别表示1.一个int值,表示递归到当前的level,当前的哪几个col被占领了,例如11011就表示我们下一个Q只能放在第三个(从第一个位置开始数)位置上了;2.一个hash table, 表示左对角线到目前为止,是否有Queen占领过了;2.一个hash table,表示右对角线是否有Queen占领过了。然后每次都去查询row上的可用格子,再去看看两个hash table上的可用格子,一起决定这一层我们选取那一(几)个作为备选项。
说说那个表示对角线的hash table,是一个Integer到boolean的映射。因为,所有某条固定左对角线上的点(row, col),row - col都是定值,那么可以用row - col表示一条左对角线嘛!同理可以用row + col表示右对角线嘛。

然后任意一个点,我们就知道它左右对角线的key了,就可以去那个hash 表里面查看是不是有Queen占领过啦。
所以,给出一个当前被占领的状态,一个左对角线被占领的状态,一个右对角线被占领的状态,我们就可以计算出下一步在哪里放Queen啦。方法如下:
private static int available(int cur_row_status,
HashMap<Integer, Boolean> left_digra_status, HashMap<Integer, Boolean> right_digra_status, int row, int n){
int avail = cur_row_status;
for(int j = 0; j < n; j++){
if((left_digra_status.containsKey(row + j) && left_digra_status.get(row + j))
|| (right_digra_status.containsKey(row - j) && right_digra_status.get(row - j))) avail = set(avail, j);
}
return avail;
}
available方法
例如,返回如果是而110011(二进制),那么中间两位是可以放Q的。
那,我们就可以定义递归函数咯哦。
private static void collectSolutions(int cur_row_status,
HashMap<Integer, Boolean> left_digra_status, HashMap<Integer, Boolean> right_digra_status,
int row, int n, int[] count){
if(row == n) {
count[0]++;
return;
}
int avail = available(cur_row_status, left_digra_status,right_digra_status, row, n);
for(int i = 0; i < n; i++){
if(!isSet(avail, i)){
left_digra_status.put(row + i, true);
right_digra_status.put(row - i, true);
collectSolutions(set(cur_row_status, i), left_digra_status, right_digra_status, row + 1,
n, count);
left_digra_status.put(row + i, false);
right_digra_status.put(row - i, false);
}
}
}
collectSolutions
count里面就放我们的计数。注意每次递归子函数返回后,要重新设置对角线。col的那个状态不用重置了,因为java函数不会改变int值的。
主函数这样写:
public static int totalNQueens(int n) {
// Start typing your Java solution below
// DO NOT write main() function
int cur_row_status = 0;
int[] count = new int[1];
HashMap<Integer, Boolean> left_digra_status = new HashMap<Integer, Boolean>();
HashMap<Integer, Boolean> right_digra_status = new HashMap<Integer, Boolean>();
collectSolutions(cur_row_status, left_digra_status, right_digra_status, 0, n, count);
return count[0];
}
然后我觉得我这方法已经不错了吧,结果还是让大集合潮湿了。
牛逼闪闪,刺瞎我的24k钛合金狗眼的位移算法来鸟。
public int totalNQueens(int n){
cnt = 0;
upper = (1<<n)-1 ;
Queen(0,0,0);
return cnt;
}
//为啥说大牛niub呢,看看我下面那个,再对比ld和rd,人大牛一眼就看出来了,没必要保存
//所有对角线信息啊。下一个状态,完全由当前状态决定!!
private void Queen(int row, int ld, int rd){//ld, left 对角线; rd, right 对角线
int pos, p;
if(row!=upper)
{
//so pos in binary is like, under current row/ld/rd restriction, what is available slot to put Q
pos = upper & (~(row | ld |rd));
while(pos!=0)//available is 1
{
p = pos & (-pos);//from right to left, the first "1" in pos
//now, we occupy the most right available position
pos = pos - p;//now take this available as ”Q“,pos kind of like a available slot marker
Queen(row+p,(ld+p)<<1,(rd+p)>>1);
}
}
else ++cnt;
}
Niubility N Queen
好一个不明觉厉,男默女泪的算法!
。。。。。
首先,再次承认和牛人的差距。
其次,反思,反思,深刻地反思。为毛牛人就知道这一点呢?其实所有中间信息都可以用一个整数来表示啊。
特别是那个左右对角线的事情,弄的本娃很郁闷。仔细想想,可不是嘛,当设置了一个Q以后,就是设置其左下方和右下方不能访问嘛。随着层次的深入(向最后一行靠近),对角线的状态可不就是左对角线左移,右对角线右移嘛。天,好有画面感的事情。
这里还有个小技巧。11100这个二进制数,怎么知道从右向左边第一个1的位置啊?
p = (pos) & (-pos)
我真是不知道这个,如果你也不知道负数在计算机中的表示方法的话,建议google之。
哦,这里有个关于这个算法的图图,看看有帮助。http://www.matrix67.com/blog/archives/266
我想去买这位blogger的书了。
总结:
1. 思考要有深度。就是说,理解一下,当前的信息到底是怎么样得出来的,而不是看表象。
2. 要有画面感。
LeetCode 笔记系列 14 N-Queen II [思考的深度问题]的更多相关文章
- LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]
题目: Given an array of non-negative integers, you are initially positioned at the first index of the ...
- LeetCode 笔记系列 18 Maximal Rectangle [学以致用]
题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones ...
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...
- LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]
题目:Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. ...
- LeetCode 笔记系列16.2 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...
- LeetCode 笔记系列16.1 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
题目: Given a string S and a string T, find the minimum window in S which will contain all the charact ...
- LeetCode 笔记系列15 Set Matrix Zeroes [稍微有一点hack]
题目:Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Fol ...
- LeetCode 笔记系列12 Trapping Rain Water [复杂的代码是错误的代码]
题目:Given n non-negative integers representing an elevation map where the width of each bar is 1, com ...
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...
随机推荐
- Json序列化之.NET开源类库Newtonsoft.Json
上代码: using System; using System.Collections; using System.Collections.Generic; using System.IO; usin ...
- find_if查找vector内对象的成员 作为菜鸟一直不会用也不敢用
用stl的find方法查找一个包含简单类型的vector中的元素是很简单的,例如 vector<string> strVec; find(strVec.begin(),strVec.end ...
- 深入学习HttpClient(一)扩展额外的功能
HttpClient作为.net4.5新增的Http库除了对于async/await形式的异步支持外,还向我们展示了其强大的扩展能力. [类库的设计] 让我们先看下Httpclient的设计图: 图中 ...
- fastjson常用操作
一. fastjson生成json字符串(JavaBean,List<JavaBean>,List<String>,List<Map<String,Object&g ...
- ApplicationListener接口中的onApplicationEvent被调用两次解决方式
Spring容器初始化完毕后,调用BeanPostProcessor这个类,这个类实现ApplicationListener接口,重写onApplicationEvent方法, 方法中就是我们自己要在 ...
- JsonNode、JsonObject常用方法
最近项目中要用json,闲暇时间,对json进行下总结. 1.JsonNode 项目中用到的jar包 import com.fasterxml.jackson.core.JsonParseExce ...
- PHP libevent扩展安装
libevent是一个基于事件驱动的高性能网络库.支持多种 I/O 多路复用技术, epoll. poll. dev/poll. select 和 kqueue 等:支持 I/O,定时器和信号等事件: ...
- 关于Cocos2d-x中自定义的调用注意事项
1.在实例类Student.h中定义一个自己的方法 public: int getSno(); 2.在实例类Student.cpp中实现这个方法 int Student::getSno(){ retu ...
- 使用PULL解析XML文件
转载博文1:http://blog.csdn.net/wangkuifeng0118/article/details/7313241 XmlPull和Sax类似,是基于流(stream)操作文件,然后 ...
- 第二百六十节,Tornado框架-内置模板方法
Tornado框架-内置模板方法 直接在html文件使用,不需要传值 Tornado默认提供的这些功能其实本质上就是 UIMethod 和 UIModule,也就是Tornado框架定义好的html文 ...